# coding=utf-8
from __future__ import absolute_import
import requests
import os
import ffmpy
import hashlib
import time

from six.moves import xrange
from celery import shared_task
from django.conf import settings
from gm_types.mimas import IMAGE_TYPE
from gm_upload.utils.image_utils import Picture
from gm_upload import upload_file

from talos.models.tractate import TractateImages
from talos.rpc import logging_exception
from qa.models.answer import AnswerImage, QuestionImage


from qa.cache import ViewRecord


def view_increase_amount(model_name, id_value, count, reverse=False):
    for _ in xrange(count):
        view_increase(model_name, id_value, reverse)


@shared_task
def view_increase(model_name, id_value, reverse=False):
    """

    :param model_name:
    :param id_value:
    :param reverse: 相反的，做减法
    :return:
    """
    view = ViewRecord(model_name)
    if reverse:
        view[id_value] = int(view[id_value] or '1') - 1
    else:
        view[id_value] = int(view[id_value] or '0') + 1

    return view[id_value]


@shared_task
def gif_create_webp(conent_id, content_type):
    """把GIF转成webp格式的图"""
    if not conent_id or not content_type:
        return

    if content_type == "answer":
        img_items = AnswerImage.objects.filter(image_type=IMAGE_TYPE.GIF, answer_id=conent_id)
    elif content_type == "question":
        img_items = QuestionImage.objects.filter(image_type=IMAGE_TYPE.GIF, question_id=conent_id)
    elif content_type == "tractate":
        img_items = TractateImages.objects.filter(image_type=IMAGE_TYPE.GIF, tractate_id=conent_id)
    else:
        return

    if not img_items:
        return

    for img_item in img_items:
        hash_key = hashlib.md5(str(time.time()).encode("utf8")).hexdigest()
        input_path = os.path.join(settings.GIF_CONVERT_PATH, "{}twp.gif".format(hash_key))
        output_path = os.path.join(settings.GIF_CONVERT_PATH, '{}twp.webp'.format(hash_key))
        img_url = Picture.get_no_watermark_path(img_item.image_url)
        res = requests.get(img_url)
        # 文件存储到本地
        with open(input_path, 'wb') as f:
            f.write(res.content)
        # 使用底层 FFmpeg 库进行转码
        ff = ffmpy.FFmpeg(
            inputs={input_path: None},
            outputs={output_path: settings.GIF_FF_WEBP}
        )
        ff.run()
        # 上传webP图片
        img_item.image_webp = upload_file(output_path)
        img_item.save()

        if os.path.exists(input_path):
            os.remove(input_path)
        if os.path.exists(output_path):
            os.remove(output_path)
