#!/usr/bin/env python
# -*- coding: utf-8 -*-

from talos.rpc import bind_context, bind
from gm_types.error import ERROR as CODES

from utils.common import convert_map_key2str
from utils.rpc import gen, get_current_user
from talos.services import (
    get_user_from_context,
)
from talos.cache.base import reply_cache
from talos.tools.replies_tool import ReplyTool
from talos.services import UserConvertService
from qa.services import QualityQuestionService, QualityReplyService, QualityAnswerService


@bind_context("qa/quality_question/create_reply")
def quality_question_create_reply(ctx, quality_answer_id, replied_id, content, images=[]):

    user = get_user_from_context(ctx)
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    replied = top_id = None
    if replied_id:
        replied = QualityReplyService.health_get(replied_id)
        top_id = replied.top_id if replied.top_id else replied.id
        answer = QualityAnswerService.health_get(replied.quality_answer_id)
    else:
        answer = QualityAnswerService.health_get(quality_answer_id)

    QualityQuestionService.quality_question_health_get(answer.quality_question_id)

    reply_info = QualityReplyService.create_reply(user.id, answer, content, replied, top_id, images)

    replied_user_id = answer.user_id
    if replied:
        replied_user_id = replied.user_id
    if replied_user_id != user.id:
        rt = ReplyTool(reply_cache, replied_user_id)
        rt.receive_quality_reply(reply_info["id"])

    # fill user info
    user_ids = [reply_info["user"]["id"]]
    if reply_info["replied_user"]:
        user_ids.append(reply_info["replied_user"]["id"])

    users_dict = UserConvertService.get_user_info_by_user_ids(user_ids)

    reply_user = users_dict.get(reply_info["user"]["id"], {})
    reply_info["user"].update(reply_user)

    reply_info["replied_user_is_author"] = False
    if reply_info["replied_user"]:
        replied_user = users_dict.get(reply_info["replied_user"]["id"], {})
        reply_info["replied_user"].update(replied_user)
        if reply_info["replied_user"]["id"] == answer.user_id:
            reply_info["replied_user_is_author"] = True

    return reply_info


@bind("qa/quality_question/reply_by_in_level_quality_question_ids")
def quality_question_reply_in_level_by_quality_question_ids(quality_question_ids, offset=0, count=10):
    """根据追问id列表获取对应的评论，对一二级评论进行了区分。

    Return: {
        quality_question_id: [
            {
                "id": reply.id,
                "quality_question_id": reply.quality_question_id,
                "quality_answer_id": reply.quality_answer_id,
                "top_id": reply.top_id,
                "replied_id": reply.replied_id,
                "user": {
                    ....
                },
                "images": {
                    "url": image.url,
                    "width": image.width,
                    "height": image.height,
                }
                "replied_user": {},
                "content": reply.content,
                "comment": [
                    {
                        "id": reply.id,
                        "quality_question_id": reply.quality_question_id,
                        "quality_answer_id": reply.quality_answer_id,
                        "top_id": reply.top_id,
                        "replied_id": reply.replied_id,
                        "user": {
                            ....
                        },
                        "replied_user": {
                            ....
                        },
                        "content": reply.content,
                        "images": []
                    }
                ]
            }
        ]
    }
    """

    # {quality_question_id: [reply_info]}
    replies = QualityReplyService.top_replies_by_quality_question_ids(
        quality_question_ids, offset=offset, count=count
    )

    top_ids = []
    for _, item in replies.items():
        top_ids.append(item["id"])

    # {top_id: [reply_info]}
    second_replies = QualityReplyService.second_replies_by_top_reply_ids(
        top_ids, offset=0, count=2
    )

    # fill second replies
    for _, rs in replies.items():
        for r in rs:
            rs["comment"] = second_replies.get(r["id"], [])

    replies = convert_map_key2str(replies)
    return replies


@bind("qa/quality_question/reply_by_quality_question_ids")
def quality_question_reply_by_quality_question_ids(quality_question_ids, offset=0, count=10):
    """根据追问id列表获取对应的评论。

    这里的评论没有区分了一二级评论。
    Return: {
        quality_question_id: [
            reply_info,
        ]
    }
    """

    # {quality_question_id: [reply_info]}
    replies = QualityReplyService.replies_by_quality_question_ids(
        quality_question_ids, offset=offset, count=count
    )

    replies = convert_map_key2str(replies)
    return replies


@bind("qa/quality_question/reply_by_quality_question_id")
def quality_question_reply_by_quality_question_id(quality_question_id, offset=0, count=10):
    """根据追问id列表获取对应的评论。

    Return: {
        "replies": [
            ...
        ],
        "rest_total": 12, # 剩余的数量
    }
    """
    result = {
        "replies": [],
        "rest_total": 0,
    }

    # {quality_question_id: [reply_info]}
    replies = QualityReplyService.replies_by_quality_question_ids(
        [quality_question_id], offset=offset, count=count
    )
    if not replies:
        return result

    result["replies"] = replies.get(quality_question_id, [])

    reply_count = QualityReplyService.count_by_quality_question_id(quality_question_id)
    rest_total = reply_count - (offset + count)
    if rest_total < 0:
        rest_total = 0

    result["rest_total"] = rest_total

    return result


@bind('qa/quality_question/reply_received')
def quality_question_reply_received(reply_ids):

    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    replies = QualityReplyService.replies_by_ids(reply_ids)

    answer_ids = set()
    replied_ids = set()
    for _, reply in replies.items():
        if reply.get("replied_id"):
            replied_ids.add(reply["replied_id"])
        else:
            answer_ids.add(reply["quality_answer_id"])

    rs = QualityReplyService.objs_by_ids(replied_ids)
    answers = QualityAnswerService.objs_by_ids(answer_ids)

    quality_question_ids = [answer.quality_question_id for answer in answers.values()]
    quality_questions = QualityQuestionService.quality_questions(quality_question_ids)

    result = {}
    for _id, reply in replies.items():
        quality_question = quality_questions.get(reply["quality_question_id"])
        info = {
            "id": _id,
            "answer_id": quality_question.answer_id,
            "content": reply["content"],
            "create_time": reply["create_time"],
            "user": reply["user"],
            "replied_user": reply["replied_user"],
        }
        info["replied_content"] = ""
        if reply.get("replied_id") and rs.get(reply["replied_id"]):
            info["replied_content"] = rs[reply["replied_id"]].content
        elif reply.get("quality_answer_id") and answers.get(reply["quality_answer_id"]):
            info["replied_content"] = answers[reply["quality_answer_id"]].content

        result[str(_id)] = info

    return result
