# -*- coding: utf-8 -*-
# from django.db.models.fields import CharField
# from django.db import models
from .image_utils import get_full_path, get_short_path
from crawler.gm_upload.gm_upload.consts import GmImageManager, IMG_TYPE


class ImgUrlField(CharField):

    def __init__(self, verbose_name=None, name=None, img_type=None, **kwargs):
        assert img_type in IMG_TYPE

        self._img_type = img_type
        # 这里如果修改了GmImageManager.get_domain()返回值，要注意下有没有影响
        self.domain = GmImageManager(img_type).get_domain()
        super(CharField, self).__init__(verbose_name, name, **kwargs)

    def to_python(self, value):
        if not value:
            return value

        try:
            return get_full_path(value, self.domain)
        except Exception:
            return value

    def from_db_value(self, value, expression, connection, context=None):
        if not value:
            return value

        try:
            return get_full_path(value, self.domain)
        except Exception:
            return value

    def get_prep_value(self, value):
        if not value:
            return value

        try:
            return get_short_path(value, self.domain)
        except Exception:
            return value
    #
    # def deconstruct(self):
    #     name, path, args, kwargs = super(ImgUrlField, self).deconstruct()
    #     kwargs['img_type'] = self._img_type
    #     return name, path, args, kwargs
