# coding=utf-8
import os

from PIL import Image
from django.conf import settings
from django.db import models
from utils.file_operation import UploadFile, DeleteFile

class UploadManager(models.Manager):

    def _addnew(self, file):
        width = None
        height = None

        path = UploadManager.calculatePath()
        filename = UploadFile(file, path)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
        size = os.path.getsize(fullname)

        try:
            img = Image.open(fullname)
            width, height = img.size
            # 缩略图压缩宽或高最大200
            if width > 1440:
                img = img.resize((1440, int((height / width) * 1440)), Image.ANTIALIAS)
                img.save(fullname)
                width, height = img.size
        except:
            pass

        instance = self.model(
            picture="%s%s" % (settings.MEDIA_URL, filename),
            width=width,
            height=height,
            file_size="%.2f" % (float(size) / 1024),
        )
        instance.save()
        return instance

    def _addnew_voice(self, file, time):

        path = UploadManager.calculatePath()
        filename = UploadFile(file, path)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
        size = os.path.getsize(fullname)

        instance = self.model(
            picture="%s%s" % (settings.MEDIA_URL, filename),
            width=200,
            height=200,
            file_size="%.2f" % (float(size) / 1024),
            voice_time=time,
        )
        instance.save()
        return instance

    @staticmethod
    def calculatePath():
        return commodity_image


commodity_image = "commodity_image/"
details_image = "details/"
parameter_image = "parameter_image/"


class Upload(models.Model):
    picture = models.CharField(verbose_name=u'图片路径', max_length=250)
    width = models.IntegerField(verbose_name=u"图片宽度", blank=True, default=0)
    height = models.IntegerField(verbose_name=u"图片高度", blank=True, default=0)
    create_time = models.DateTimeField(verbose_name=u'上传时间', auto_now_add=True, editable=False)
    file_size = models.FloatField(verbose_name="文件大小", blank=True, default=0)

    objects = UploadManager()

    class Meta:
        db_table = 'system_upload'
        verbose_name = u'文件上传'
        ordering = ['-create_time']
        index_together = (
            'create_time',
        )
        default_permissions = ()

    def del_images(self):
        picture = self.picture
        self.delete()
        DeleteFile(picture)

    def get_path(self):
        return '%s%s' % (settings.SERVER_DOMAIN, self.picture)

    def get_picture(self):
        return self.picture
