# -*- coding: UTF-8 -*-
import requests
import json
try:
    import StringIO
except:
    from io import StringIO

from .consts import image_type, IMG_TYPE, qiniu_video
from crawler.gm_upload.gm_upload.utils.filenameutils import gen_rnd_filename, store_picture_and_get_key
from crawler.gm_upload.gm_upload.utils.image_utils import get_full_path
from crawler.gm_types.gm_types.error import ERROR
from .consts import GmImageManager


def upload(image_file, img_type=IMG_TYPE.DIARY, save_name=None, platform='qiniu'):
    """ 上传图片并返回全路径
    """
    return upload_with_short(image_file, img_type, save_name, platform)[0]


def upload_file(file_path, img_type=IMG_TYPE.NOWATERMARK, save_name=None, platform='qiniu'):
    """ 上传本地文件并返回全路径
        """
    return upload_file_with_short(file_path, img_type, save_name, platform)[0]


def get_private_url(key, img_type=IMG_TYPE.INSTALLMENT, time=3600, platform='qiniu'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    manager = GmImageManager(img_type)
    return QiniuTool.get_private_url(manager.get_domain(), key, time)


def get_private_url_for_long(url, time=3600, platform='qiniu'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    return QiniuTool.get_pritvate_url(url, time)


# 上传本地文件同时获得相对路径和全路径 backend里面需要给客户端返回相对路径
# 用来上传video对应的webp图片
def upload_file_with_short(file_path, img_type=IMG_TYPE.WATERMARK, save_name=None, platform='qiniu'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    manager = GmImageManager(img_type)
    prefix = manager.get_prefix()
    if not save_name:
        save_name = gen_rnd_filename()
    if prefix:
        save_name = prefix + '/' + save_name
    QiniuTool.upload_file(file_path, save_name, manager.get_bucket())
    return get_full_path(save_name, manager.get_domain()), save_name


# 上传同时获得相对路径和全路径 backend里面需要给客户端返回相对路径
def upload_with_short(image_file, img_type=IMG_TYPE.DIARY, save_name=None, platform='qiniu'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    manager = GmImageManager(img_type)
    prefix = manager.get_prefix()
    if not save_name:
        save_name = gen_rnd_filename()
    if prefix:
        save_name = prefix + '/' + save_name
    QiniuTool.upload(image_file, save_name, manager.get_bucket())
    return get_full_path(save_name, manager.get_domain()), save_name


def get_video_upload_token():
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    return QiniuTool.get_token(qiniu_video['bucket'])


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


def set_video_watermark(filename, newfilename, bucket_name='video', water_mark_url='https://heras.igengmei.com/logo-video-watermark.png', pipeline='gm-video'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    return QiniuTool.set_video_watermark(filename, newfilename, bucket_name, water_mark_url, pipeline)


# 视频截取/转码
def video_clipping(filename, new_filename='', video_type='mp4', bucket_name='video', pipeline='gm-video',
                   water_mark_url='https://heras.igengmei.com/logo-video-watermark.png',
                   start_time=1, duration=2, audio_no=1):
    if not new_filename:
        new_filename = gen_rnd_filename(ext=video_type)
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    return QiniuTool.video_clipping(filename, new_filename, video_type, bucket_name, water_mark_url,
                                    pipeline, start_time, duration, audio_no)


def video_delete(key, bucket_name='video'):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    QiniuTool.delete(key, bucket_name)


def batch_move_watermark_pic_to_no_watermark(filsname_list, bucket_name, new_bucket_name):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    return QiniuTool.batch_move_pic(filsname_list, bucket_name, new_bucket_name)


def set_image_water_mark_for_picture_and_save_to_qiniu(
        img_url,
        water_mark_url,
        dissolve=100,
        gravity='NorthEast',
        dx=40,
        dy=40
):
    from crawler.gm_upload.gm_upload.utils.qiniu_tool import QiniuTool
    f_url = QiniuTool.set_picture_watermark(
        img_url=img_url,
        water_mark_url=water_mark_url,
        dissolve=dissolve,
        gravity=gravity,
        dx=dx,
        dy=dy
    )
    return fetch_picture_and_save_to_qiniu(f_url)


def get_video_base_info(video_url, suffix="?avinfo"):
    """
    获取视频的基本信息
    :param video_url: 完整的视频地址
    :param suffix: 参数
    :return:
    """
    full_path = video_url + suffix
    resp = requests.get(full_path)
    stream_info = {}

    if resp.status_code == requests.codes.ok:
        data = json.loads(resp.text)
        for item in data.get("streams", []):
            if item.get("codec_type", "") == "video":
                stream_info = item
                break

    ret_data = {
        'width': stream_info.get("width", 0),
        'height': stream_info.get("height", 0),
    }
    return ret_data
