from talos.libs.data_sync import AbstractView
from talos.backbone.data_sync import ddsm, JoinedDataSource
from talos.backbone.rpc import RPCMixin

from api.models import Problem, ProblemTag  # TODO: replace with talos.models


rpc_invoker = RPCMixin.get_rpc_invoker()


def get_topic_tags_by_user_ids(user_ids):
    if len(user_ids) == 0:
        return []

    topics = rpc_invoker['topic/get_topic_info_by_user_ids'](user_ids=user_ids, topic_id_only=True)
    topics = topics.unwrap()

    result = {
        user_id: {
            'user_id': user_id,
            'topics': []
        } for user_id in user_ids
    }
    if not topics:
        return result.values()

    topic_id2user_map = {t['id']:t['user_id'] for t in topics}
    topic_tags = rpc_invoker['topic/get_tags_by_topic_ids'](ids=topic_id2user_map.keys())
    topic_tags = topic_tags.unwrap()
    for topic_tag in topic_tags:
        user_id = topic_id2user_map[topic_tag['id']]
        result[user_id]['topics'].append({
            'id':topic_tag['id'],
            'tags':topic_tag['data'],
        })

    result = result.values()
    return result


user_topic_tags_view = AbstractView(
    data_source=JoinedDataSource(  # TODO: replace data source
        ddsm.model_data_source(Problem),
        ddsm.model_data_source(ProblemTag),
        ddsm.foreign_key_data_relation(ProblemTag.problem.field).reversed
    ),
    view_function=get_topic_tags_by_user_ids
)
