# coding:utf-8
import json
import time

from gm_types.user import (
    STAT_LOG_ACTION_CONTENT_TYPE,
    STAT_LOG_USER_ACTION,
)

from gm_types.gaia import (
    TOP_CONTENT_RELATED_TYPE,
)

from api.tool.user_tool import get_user_from_context
from group.models import GroupTopicRelation
from group.service import (
    TopicService,
    GroupService,
    TopContentService,
)
from utils.time_tools import datetime2timestamp
from rpc.decorators import bind, bind_context
from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES
from rpc.decorators import cache_page


@bind_context('api/topic/detail')
def topic_detail(ctx, topic_id):

    user = get_user_from_context(ctx)

    topic = TopicService.safe_get(topic_id)

    detail = TopicService.detail(topic)
    topic_tagv3_dic = TopicService.topic_relation_tag_v3s_by_ids([topic_id])

    detail["joined"] = TopicService.is_follow(topic_id, user.id) if user else False
    group_relation = GroupTopicRelation.objects.filter(topic_id=topic_id, is_online=True).first()
    if group_relation:
        detail["fans_num"] = GroupService.follow_num(group_relation.group_id)
    detail.update({
        "tags_v3": topic_tagv3_dic.get(topic.id, []),
    })

    return detail


@bind('api/topic/simple_info_by_topic_id')
def topics_by_topic_id(topic_id):

    group = GroupService.get_group_by_topic_id(topic_id)
    topic = TopicService.safe_get(topic_id)

    topics = []
    if group:
        topics = TopicService.list_topics_by_group_id(group.id)

    info = {
        "topics": topics,
        "top_card_id": topic.top_card_id,
        "top_card_type": topic.top_card_type,
        "punch_entrance": topic.punch_entrance and json.loads(topic.punch_entrance) or {},
        "hit_rank_start_time": topic.hit_rank_start_time and datetime2timestamp(topic.hit_rank_start_time),
        "hit_rank_end_time": topic.hit_rank_end_time and datetime2timestamp(topic.hit_rank_end_time),
        "group": {},
        "group_topic_type": topic.group_topic_type,
        "is_single_feed": topic.is_single_feed,
        "top_contents": TopContentService.get_top_content_data(   # 置顶数据
            related_type=TOP_CONTENT_RELATED_TYPE.TOPIC,
            related_id=topic_id
        ),
    }

    if group:
        info["group"] = {
            "id": group.id,
            "name": group.name,
            "group_type": group.group_type,
        }

    return info


@bind_context('api/topic/follow')
def topic_follow(ctx, topic_id):

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

    TopicService.follow(topic_id, user.id)
    ctx.logger.app(
        user_id=user.id,
        content_id=topic_id,
        timestamp=time.time(),
        action=STAT_LOG_USER_ACTION.FOLLOW,
        content_type=STAT_LOG_ACTION_CONTENT_TYPE.GROUP_TOPIC,
    )


@bind_context('api/topic/unfollow')
def topic_unfollow(ctx, topic_id):

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

    TopicService.unfollow(topic_id, user.id)


@bind('api/topic/add_content')
def topic_add_content(topic_id, card_type, card_id):

    TopicService.add_content(topic_id, card_type, card_id)


@bind("api/topic/tags")
@cache_page(60 * 1)
def list_tags_by_topic_id(topic_id):

    topic = TopicService.safe_get(topic_id)

    return TopicService.tags_by_topic_id(topic.id)


@bind("api/topic/list_by_ids")
def list_tags_by_topic_ids(topic_ids):

    topics = []
    for topic_id in topic_ids:
        try:
            topic = TopicService.safe_get(topic_id)
        except:
            continue

        topics.append(TopicService.detail(topic))

    return topics


@bind("api/topic/list_by_tag_ids")
def list_tags_by_tag_ids(tag_ids):

    topics_info = TopicService.list_by_tag_ids(tag_ids)

    return topics_info


@bind("api/topic/list_by_tag_v3_ids")
def list_tags_by_tag_ids(tag_ids):
    if not tag_ids:
        return {}
    topics = TopicService.list_by_tag_v3_ids(tag_ids)

    return topics


@bind('api/topic/get_tag2topic_map')
def get_tag2topic_map():
    return TopicService.get_tag2topic_map()
