#!/usr/bin/env python
# encoding=utf-8
from six.moves import urllib
import six
import json
import requests

SUFFIX_MAP = {
    '-half': 'imageView2/2/w/320/h/320/q/85',
    '-small': 'imageView2/2/w/640/q/85',
    '-thumb': 'imageView2/2/w/120/h/120/q/85',
    '-w': 'imageView2/2/w/640/h/640/q/100',
    '-web': 'imageView2/2/w/150/h/150/q/85',
    '-mid': 'imageView2/2/w/450/q/85',
    '-200': 'imageView2/2/w/200/h/200/q/85',
    '-wr': 'imageView2/2/w/640/q/85',
    '-half_blur': 'imageView2/2/w/320/h/320/q/85',
    '-slimwidth': 'imageView2/2/w/230/h/153/q/85',
    '-halfjpg': 'imageView2/2/w/375/h/300/q/75',
    '-thumbjpg': 'imageView2/2/w/120/h/120/q/85',
    '-aspectscale800': 'imageView2/0/w/800/h/9999/format/jpg/q/100|imageslim',
}


def _get_watermark_path(pathname, size):
    if not SUFFIX_MAP.get(size):
        return pathname

    path, watermark = pathname.split("?")
    return path + "?" + SUFFIX_MAP.get(size) + urllib.parse.quote("|") + watermark


def get_domain(domain):
    """ domain 补全http/https, 若domain不带http/https前缀，默认加http前缀
    """
    # 若domain不带http/https前缀，默认加http前缀
    if not domain.startswith('http://') and not domain.startswith('https://'):
        domain = 'http://' + domain
    if not domain.endswith('/'):
        domain = domain + '/'
    return domain


def get_full_path(path_name, domain, extra=''):
    domain = get_domain(domain)
    try:
        p = urllib.unquote(path_name)
        path_name = p
    except:
        pass

    # add https
    if path_name and ( path_name.startswith('http://') or path_name.startswith('https://') ):
        full_path = path_name

    elif path_name:
        full_path = urllib.parse.urljoin(domain, path_name)

    else:
        full_path = ''

    return full_path + extra


def get_short_path(path_name, domain, extra=''):
    domain = get_domain(domain)
    if path_name:
        if domain in path_name:
            short_path = path_name.replace(domain, '')
        else:
            short_path = path_name
    else:
        short_path = ''
    return short_path + extra


def get_w_path(image_name):
    return get_full_path(image_name, '-w')


def get_thumb_path(image_name):
    return get_full_path(image_name, '-thumb')


class ImageUrlBase(object):
    qiniu_host = "https://pic.igengmei.com"
    qiniu_temp_host = 'http://pic-tmp.igengmei.com'
    img_cdn = 'http://imgcdn.wanmeizhensuo.com'
    qiniu_cdn = 'http://wanmeizhensuo.qiniudn.com'

    def __init__(self, base_url):
        if not base_url:
            base_url = None
        else:
            assert isinstance(base_url, six.string_types)
            if not base_url.startswith('http://') and not base_url.startswith('https://'):
                base_url = urllib.parse.urljoin(self.qiniu_host, base_url)

        base_url = self.domain_name_replace(base_url)
        self._base_url = base_url

    def delete_suffix(self):
        if self._base_url is None:
            return

        pos = self._base_url.find('-')
        if pos != -1:
            self._base_url = self._base_url[:pos]

    def _suffix(self, sfx):
        self.delete_suffix()

        if not self._base_url:
            return ''

        if "watermark" in self._base_url and "?" in self._base_url:
            return _get_watermark_path(self._base_url, sfx)

        if self._base_url:
            return self._base_url + sfx

    @classmethod
    def domain_name_replace(cls, url_name):
        if not url_name:
            return ''

        url_name = url_name.replace('hera.s.gmei.com', 'hera.s.igengmei.com')
        url_name = url_name.replace('pic.gmei.com', 'pic.igengmei.com')
        url_name = url_name.replace('pic.gengmei.cc', 'pic.igengmei.com')
        url_name = url_name.replace('hera.s.gengmei.cc', 'pic.igengmei.com')
        # hera.s to heras
        url_name = url_name.replace('hera.s.igengmei.com', 'heras.igengmei.com')

        url_name = url_name.replace(cls.img_cdn, cls.qiniu_host)
        url_name = url_name.replace(cls.qiniu_cdn, cls.qiniu_host)

        return url_name


class Picture(ImageUrlBase):
    @property
    def raw(self):
        return self._suffix('')

    @property
    def watermarked(self):
        """
        watermark, width <= 640px, scaled
        """
        return self._suffix('-w')

    @property
    def thumb(self):
        """
        120px * 120px, cropped
        """
        return self._suffix('-thumb')

    @property
    def web(self):
        """
        150px * 150px, cropped
        """
        return self._suffix('-web')

    @property
    def half(self):
        """
        320px * 320px, cropped
        """
        return self._suffix('-half')

    @property
    def half_blur(self):
        """
        320px * 320px, cropped  fuzzy
        详见：http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=1841134
        """
        return self._suffix('-half_blur')

    @property
    def wide(self):
        """
        640px * 480px, cropped
        """
        return self._suffix('-wide')

    @property
    def smallwide(self):

        return self._suffix('-smallwide')

    @property
    def mid(self):
        """
        watermark, width <= 450px, scaled
        """
        return self._suffix('-mid')

    @property
    def small(self):
        """
        320px * 128px, cropped
        """
        return self._suffix('-small')

    @property
    def new(self):
        """
        640px * auto, cropped
        """
        return self._suffix('-new')

    @property
    def p_200(self):
        """
        200px *200px
        """
        return self._suffix('-200')

    @property
    def slimwidth(self):
        """
        230x * 153px, cropped
        """
        return self._suffix('-slimwidth')

    @property
    def half_jpg(self):
        """
        375px * 375px, cropped
        """
        return self._suffix('-halfjpg')

    @property
    def thumb_jpg(self):
        """
        120px * 120px, cropped
        :return:
        """
        return self._suffix('-thumbjpg')

    @property
    def aspectscale_800(self):
        return self._suffix('-aspectscale800')

    @property
    def aspectscale(self):
        return self._suffix('-aspectscale?v=1')

    @property
    def no_watermark(self):
        return self._suffix('-wn?v=1')

    @property
    def no_change(self):
        return self._suffix('-s')

    @property
    def webp(self):
        return self._suffix('-webp')

    @classmethod
    def get_200_path(cls, base_url):
        obj = cls(base_url)
        return obj.p_200

    @classmethod
    def get_thumb_path(cls, base_url):
        obj = cls(base_url)
        return obj.thumb

    @classmethod
    def get_half_path(cls, base_url):
        obj = cls(base_url)
        return obj.half

    @classmethod
    def get_wide_path(cls, base_url):
        obj = cls(base_url)
        return obj.wide

    @classmethod
    def get_smallwide_path(cls, base_url):
        obj = cls(base_url)
        return obj.smallwide

    @classmethod
    def get_w_path(cls, base_url):
        obj = cls(base_url)
        return obj.watermarked

    @classmethod
    def get_full_path(cls, path_name, extra=''):
        if not path_name:
            return ''

        if not path_name.startswith('http://') and not path_name.startswith('https://'):
            path_name = urllib.parse.urljoin(cls.qiniu_host, path_name)

        path_name = cls.domain_name_replace(path_name)

        if path_name and path_name.endswith(extra):
            extra = ''
        elif isinstance(extra, tuple):
            extra = extra[0]

        if "watermark" in path_name and "?" in path_name:
            return _get_watermark_path(path_name, extra)

        return path_name + extra

    @classmethod
    def get_short_path(cls, path_name, extra=''):
        if not path_name:
            return ''

        if cls.img_cdn in path_name:
            short_path = path_name.replace(cls.img_cdn + "/", '')
        elif cls.qiniu_cdn in path_name:
            short_path = path_name.replace(cls.qiniu_cdn + "/", '')
        elif cls.qiniu_host in path_name:
            short_path = path_name.replace(cls.qiniu_host + "/", '')
        elif cls.qiniu_temp_host in path_name:
            short_path = path_name.replace(cls.qiniu_temp_host + "/", '')
        else:
            short_path = path_name

        return short_path + extra

    @classmethod
    def get_temp_image_path(cls, path_name):
        return urllib.parse.urljoin(cls.qiniu_temp_host, path_name)

    @classmethod
    def get_half_blur_path(cls, base_url):
        obj = cls(base_url)
        return obj.half_blur

    @classmethod
    def get_slimwidth_path(cls, base_url):
        obj = cls(base_url)
        return obj.slimwidth

    @classmethod
    def get_half_jpg_path(cls, base_url):
        obj = cls(base_url)
        return obj.half_jpg

    @classmethod
    def get_thumb_jpg_path(cls, base_url):
        obj = cls(base_url)
        return obj.thumb_jpg

    @classmethod
    def get_image_base_info(cls, url, suffix='-imageinfo?ref'):
        full_path = url + suffix
        resp = requests.get(full_path)
        data = json.loads(resp.text)
        ret_data = {
            'width': '',
            'height': ''
        }
        if resp.status_code == 200:
            ret_data['width'] = data['width']
            ret_data['height'] = data['height']

        return ret_data

    @classmethod
    def get_aspectscale_800_path(cls, base_url):
        obj = cls(base_url)
        return obj.aspectscale_800

    @classmethod
    def get_aspectscale_path(cls, base_url):
        obj = cls(base_url)
        return obj.aspectscale

    @classmethod
    def get_no_watermark_path(cls, base_url):
        obj = cls(base_url)
        return obj.no_watermark

    @classmethod
    def get_no_change_path(cls, base_url):
        obj = cls(base_url)
        return obj.no_change

    @classmethod
    def get_webp_path(cls, base_url):
        obj = cls(base_url)
        return obj.webp
