# 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.service import (
    GroupService,
    TopicService,
    TopContentService,
)
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/group/detail')
def group_detail(ctx, group_id):

    user = get_user_from_context(ctx)

    group = GroupService.safe_get(group_id)

    detail = GroupService.detail(group)
    detail["joined"] = GroupService.is_follow(group_id, user.id) if user else False

    join_users = GroupService.join_users(group_id)
    detail["join_list"] = join_users
    detail["join_num"] = GroupService.follow_num(group_id)

    group_tagv3_dic = GroupService.group_relation_tag_v3s_by_ids([group_id])

    detail.update({
        "tags_v3": group_tagv3_dic.get(group.id, []),
    })

    return detail


@bind('api/group/simple_info_by_group_id')
def topics_by_group_id(group_id):

    topics = TopicService.list_topics_by_group_id(group_id)
    group = GroupService.safe_get(group_id)

    return {
        "topics": topics,
        "top_card_id": group.top_card_id,
        "top_card_type": group.top_card_type,
        "punch_entrance": group.punch_entrance and json.loads(group.punch_entrance) or {},
        "group_type": group.group_type,
        "is_single_feed": group.is_single_feed,
        "top_contents": TopContentService.get_top_content_data(  # 置顶数据
            related_type=TOP_CONTENT_RELATED_TYPE.GROUP,
            related_id=group_id
        ),
    }


@bind_context('api/group/follow')
def group_follow(ctx, group_id):

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

    GroupService.follow(group_id, user.id)
    ctx.logger.app(
        user_id=user.id,
        content_id=group_id,
        timestamp=time.time(),
        action=STAT_LOG_USER_ACTION.FOLLOW,
        content_type=STAT_LOG_ACTION_CONTENT_TYPE.GROUP,
    )


@bind_context('api/group/unfollow')
def group_unfollow(ctx, group_id):

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

    GroupService.unfollow(group_id, user.id)


@bind('api/group/bulk_follow')
def group_bulk_follow(user_id, group_ids):
    """
    用户 小组 批量关注
    :param user_id:
    :param group_ids:
    :return:
    """
    valid_follow_nums = 0  # 有效关注数

    if all([user_id, group_ids]):
        for group_id in group_ids:
            try:
                GroupService.follow(group_id, user_id)
                valid_follow_nums += 1
            except:
                continue

    return valid_follow_nums  # 返回关注成功的次数


@bind('api/group/add_content')
def group_add_content(group_id, card_type, card_id):

    GroupService.add_content(group_id, card_type, card_id)


@bind("api/group/tags")
@cache_page(60 * 1)
def list_tags_by_polymer_id(group_id):

    group = GroupService.safe_get(group_id)

    return GroupService.tags_by_group_id(group.id)


@bind("api/group/list_by_ids")
def list_tags_by_polymer_id(group_ids):

    groups = []

    for group_id in group_ids:
        try:
            group = GroupService.safe_get(group_id)
        except:
            continue

        groups.append(GroupService.detail(group))

    return groups


@bind("api/group/other_group_ids_by_topic_id")
def other_group_ids_by_topic_id(group_id, topic_ids):

    topic_ids = GroupService.other_group_ids_by_topic_ids(group_id, topic_ids)
    return topic_ids


@bind('api/groups/by_tag_v3_ids')
def get_group_by_tag_v3_ids(tag_ids):
    if not tag_ids:
        return {}
    groups = GroupService.list_by_tag_v3_ids(tag_ids)

    return groups


@bind('api/groups/get_group_and_topic_id_by_tag_v3_ids')
def get_group_and_topic_by_tag_v3_ids(tag_ids):
    return {
        'group': GroupService.list_ids_by_tag_v3_ids(tag_ids),
        'topic': TopicService.list_ids_by_tag_v3_ids(tag_ids)
    }


@bind('api/groups/get_tag2group_map')
def get_tag2group_map():
    return GroupService.get_tag2group_map()
