# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from gm_upload import IMG_TYPE
from gm_upload import ImgUrlField

from talos.libs.image_utils import get_full_path, get_short_path
from talos.models.diary.diary import Diary
from utils.common import convert_image


class PreOperationImage(models.Model):
    class Meta:
        verbose_name = u'术前图'
        verbose_name_plural = u'术前图'
        db_table = 'api_preoperationimage'
        app_label = 'talos'

    topic = models.ForeignKey('talos.Problem', related_name='pre_operation_images', null=True)
    diary = models.ForeignKey(Diary, related_name='pre_operation_images', null=True)
    image_url = ImgUrlField(img_type=IMG_TYPE.PREOPERATIONIMAGE, max_length=300, verbose_name=u'图片地址')
    cover_image_url = ImgUrlField(img_type=IMG_TYPE.PREOPERATIONIMAGE, max_length=300, verbose_name=u'封面图片地址')
    taken_time = models.DateTimeField(verbose_name=u'拍摄时间', null=True)
    is_cover = models.BooleanField(verbose_name=u'是否封面', default=False)

    def get_image_info(self):
        images = convert_image(self.image_url, watermark=True)
        images.update({
            'desc': '',
            'cover_image_url': self.get_cover_img_url(),
            'is_cover': self.is_cover,
            'image_name': get_short_path(self.image_url),  # 5.9.3新增字段
        })

        return images

    def get_cover_img_url(self):
        if self.cover_image_url:
            return get_full_path(self.cover_image_url, '-w')
        else:
            return get_full_path(self.image_url, '-w')

    def __unicode__(self):
        return u'<%s><Topic:%s><Image_url: %s>' % (self.id, self.topic, self.image_url)