# coding=utf-8

from PIL import Image

from django.db import models
from django.conf import settings
from django.utils import timezone

from utils.file_operation import UploadFile, DeleteFile


class ImagesManager(models.Manager):
    def _addnew(self, user, type, file, size=None):
        width = None
        height = None

        path = ImagesManager.calculatePath(type)
        filename = UploadFile(file, path)
        fullname = "%s%s" % (settings.MEDIA_ROOT, filename)

        try:
            img = Image.open(fullname)
            width, height = img.size
            # 缩略图压缩宽或高最大200
            if width > 200 or height > 200:
                if width > height:
                    size = (200, int(height * 200 / width))
                elif width < height:
                    size = (int(width * 200 / height), 200)
                else:
                    size = (200, 200)
                img = img.resize(size, Image.ANTIALIAS)
                img.save(fullname)
                width, height = img.size
        except:
            pass
        instance = self.model(
            user=user,
            type=type,
            picture="%s%s" % (settings.MEDIA_URL, filename),
            width=width,
            height=height,
            create_time=timezone.now()
        )
        instance.save()
        return instance

    @staticmethod
    def calculatePath(type):
        path_map = {
            Images.COMMODITY_SHOW_IMAGE: commodity_show_image,
            Images.COMMODITY_DETAILS_IMAGE: commodity_details_image,
            Images.COMMODITY_CAROUSEL_IMAGE: commodity_carousel_image,
        }
        return path_map[type]


commodity_show_image = "commodity/show/"
commodity_details_image = "commodity/details/"
commodity_carousel_image = "commodity/carousel/"


class Images(models.Model):
    COMMODITY_SHOW_IMAGE = 1
    COMMODITY_DETAILS_IMAGE = 2
    COMMODITY_CAROUSEL_IMAGE = 3
    TYPE_CHOICES = (
        (COMMODITY_SHOW_IMAGE, u'商品缩略图'),
        (COMMODITY_DETAILS_IMAGE, u'商品详情图'),
        (COMMODITY_CAROUSEL_IMAGE, u'商品轮播图'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'操作人', on_delete=models.PROTECT)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类型")
    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'上传时间', default=timezone.now, editable=False)

    objects = ImagesManager()

    class Meta:
        db_table = "images"
        verbose_name = u'图片'
        ordering = ['-create_time']
        index_together = (
            'type',
            '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)
