# coding: utf-8

import json

from communal.cache.push import personalize_push_cache as push_cache
from talos.rpc import get_current_rpc_invoker

rpc_invoker = get_current_rpc_invoker()


class Tag2GroupTopic(object):
    """标签映射到小组话题"""
    CACHE_KEY_ACTION_TAG_2_GROUP_MAP = 'mimas:communal:tag2group_map:{}'
    CACHE_KEY_ACTION_TAG_2_TOPIC_MAP = 'mimas:communal:tag2topic_map:{}'

    @classmethod
    def get_topic_ids_with_tag_v3(cls, tag_v3_id):
        if not tag_v3_id:
            return []

        cache_key = cls.CACHE_KEY_ACTION_TAG_2_TOPIC_MAP.format(tag_v3_id)
        topic_ids = push_cache.get(cache_key)
        if not topic_ids:
            res = rpc_invoker["api/topic/list_by_tag_v3_ids"](tag_ids=[tag_v3_id]).unwrap()
            topic_ids = res.get(str(tag_v3_id), [])
            push_cache.set(cache_key, json.dumps(topic_ids), 3600)
            return topic_ids

        return json.loads(topic_ids)
