# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import requests
from io import BytesIO
from urllib import parse as urlparse
from django.conf import settings

from gm_upload.utils.filenameutils import store_picture_and_get_key


imgcdn = u'http://imgcdn.wanmeizhensuo.com/'
qiniucdn = u'http://wanmeizhensuo.qiniudn.com/'


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

    path_name = path_name.replace('hera.s.gmei.com', 'hera.s.igengmei.com')
    path_name = path_name.replace('pic.gmei.com', 'pic.igengmei.com')

    path_name = path_name.replace('pic.gengmei.cc', 'pic.igengmei.com')
    path_name = path_name.replace('hera.s.gengmei.cc', 'pic.igengmei.com')

    path_name = path_name.replace('http://hera.s.igengmei.com', 'https://heras.igengmei.com')
    path_name = path_name.replace('http://pic.igengmei.com', 'https://pic.igengmei.com')

    try:
        p = urlparse.unquote(path_name)
        path_name = p
    except:
        pass

    if path_name and (path_name.startswith('http://') or path_name.startswith('https://')):
        full_path = path_name
        full_path = full_path.replace(imgcdn, settings.QINIU_CDN_HOST)
        full_path = full_path.replace(qiniucdn, settings.QINIU_CDN_HOST)

    elif path_name:
        if imgcdn in path_name:
            full_path = path_name.replace(imgcdn, settings.QINIU_CDN_HOST)
        elif qiniucdn in path_name:
            full_path = path_name.replace(qiniucdn, settings.QINIU_CDN_HOST)
        else:
            full_path = urlparse.urljoin(settings.QINIU_CDN_HOST, path_name)

    else:
        full_path = ''

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


def get_temp_image_path(path_name):
    return urlparse.urljoin(settings.QINIU_TEMP_CDN_HOST, path_name)


def get_short_path(path_name, extra=''):
    if path_name:
        if imgcdn in path_name:
            short_path = path_name.replace(imgcdn, '')
        elif qiniucdn in path_name:
            short_path = path_name.replace(qiniucdn, '')
        elif settings.QINIU_CDN_HOST in path_name:
            short_path = path_name.replace(settings.QINIU_CDN_HOST, '')
        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):
    if not image_name:
        image_name = 'img%2Fuser_portrait.png'
    return get_full_path(image_name, '-thumb')


def fetch_picture_and_save_to_qiniu_v2(url):
    if not url:
        return ''
    img = requests.get(url, timeout=5, verify=False)
    img = BytesIO(img.content)
    return store_picture_and_get_key(img)
