# -*- coding: utf-8 -*-

from __future__ import absolute_import
from django.conf import settings
from celery import shared_task

from gm_types.gaia import VIDEO_CODE_STATUS
from gm_types.push import PUSH_INFO_TYPE, AUTOMATED_PUSH
from gm_types.mimas.qa import VIDEO_SOURCE_TYPE
from gm_protocol import GmProtocol

from utils.common import replace_video_url_for_rich_text
from utils.rpc import get_rpc_invoker
from utils.rpc import logging_exception
from utils.push import push_task_to_user_multi, special_push_limit

from talos.cache.base import community_video_handle_cache

from qa.models.answer import Question, Answer
from talos.models.topic import Problem, VideoLibrary


@shared_task
def common_push(uname, uid, topic_id, push_type, question_title=None):
    """
    关注的用户发 问题帖、回答帖、直播帖
    :param user: 用户对象
    :param topic_id: 帖子id
    :param push_type:question-问题帖,answer-回答帖，live-直播帖
    :return:
    """

    if not uid:
        return

    if uid == settings.SUOZHANG_UID:
        return

    if uname.startswith(u'更美用户'):
        uname = u'匿名美人'

    try:
        user_ids = get_rpc_invoker()['api/user/get_all_fans'](user_id=uid).unwrap()
    except Exception:
        logging_exception()
        return

    alert = u'你关注的{0}发帖了！快去看看ta说了什么～'.format(uname)
    if push_type == 'question':
        push_url = GmProtocol().get_question_detail(topic_id)
        alert = u'你关注的 @{user_name} 发布了新的话题！快去看看 ta 说了什么~'.format(user_name=uname)
        p_type = AUTOMATED_PUSH.FOLLOWED_USER_PAID_A_QUESTION
    elif push_type == 'answer':
        push_url = GmProtocol().get_answer_list(topic_id)
        alert = u'你关注的 @{user_name} 刚刚在“{question_name}”下进行了回答'.format(user_name=uname, question_name=question_title)
        p_type = AUTOMATED_PUSH.FOLLOWED_USER_IS_ANSWER_A_POST
    elif push_type == 'live':
        push_url = GmProtocol().get_live_list(topic_id)
        p_type = AUTOMATED_PUSH.FOLLOWED_USER_PAID_A_QUESTION
    else:
        push_url, p_type = '', None

    #user_ids = [user_id for user_id in user_ids if special_push_limit(user_id, "user_released_topic", uid)]

    if user_ids and push_url:
        kwargs = {
            "user_ids": user_ids,
            "platform": ['android', 'iPhone'],
            "alert": alert,
            "extra": {
                'type': PUSH_INFO_TYPE.GM_PROTOCOL,
                'msgType': 4,
                'pushUrl': push_url,
                'push_url': push_url,
            },
            "push_type": p_type,
        }
        push_task_to_user_multi(**kwargs)


@shared_task
def inviter_answered_push_to_user(user_ids, answer_id, nickname):
    """
    被邀请者回答完问题，即刻推送消息给邀请者
    :param user_ids:  list 类型 user_ids
    :param answer_id:  被邀请者 回答的id
    :param nickname:  被邀请者的昵称
    :return:
    """
    push_url = GmProtocol().get_answer_list(answer_id)
    kwargs = {
        "user_ids": user_ids,
        "platform": ['android', 'iPhone'],
        "alert": u'{nickname}回答了您邀请的问题，赶紧去看看他的解答哦~'.format(nickname=nickname),
        "extra": {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'msgType': 4,
            'pushUrl': push_url,
            'push_url': push_url,
        },
        "labels": {},  # 不知道是否需要埋点，先预留
        "push_type": AUTOMATED_PUSH.QUESTION_POSTED_ANSWER,
    }
    push_task_to_user_multi(**kwargs)


@shared_task
def convert_rich_text_video_url():
    """从缓存中读数据，处理"""

    def get_model_param(_type):
        if _type == VIDEO_SOURCE_TYPE.QUESTION:
            _model = Question
            _param = "content"
        elif _type == VIDEO_SOURCE_TYPE.ANSWER:
            _model = Answer
            _param = "content"
        elif _type == VIDEO_SOURCE_TYPE.ARTICLE:
            _model = Problem
            _param = "answer_richtext"
        else:
            _model = None
            _param = None

        return _model, _param

    need_del_keys = []

    for v in community_video_handle_cache.sscan_iter("video_handle_cache", count=1):

        if isinstance(v, bytes):
            v = v.decode()

        _id, _type = v.split(":")
        _model, _param = get_model_param(int(_type))
        if not _model:
            continue

        video_dic = dict(VideoLibrary.objects.filter(
            source_id=int(_id),
            video_type=int(_type),
            persistent_status=VIDEO_CODE_STATUS.SUCCESS
        ).values_list("raw_video_url", "water_video_url"))

        if not video_dic:
            continue

        obj = _model.objects.filter(id=int(_id)).first()
        if not obj:
            continue

        if int(_type) in (VIDEO_SOURCE_TYPE.ANSWER, VIDEO_SOURCE_TYPE.QUESTION):
            raw_rich_text = getattr(obj, "content", "")

        elif int(_type) in (VIDEO_SOURCE_TYPE.ARTICLE, ):
            raw_rich_text = getattr(obj, "answer_richtext", "")

        else:
            raw_rich_text = ""

        new_rich_text, replace_all = replace_video_url_for_rich_text(raw_rich_text, video_dic)

        if replace_all:
            setattr(obj, _param, new_rich_text)
            obj.save(update_fields=[_param])
            need_del_keys.append(v)

    if need_del_keys:
        community_video_handle_cache.srem("video_handle_cache", *need_del_keys)
