# -*- coding: UTF-8 -*-

from celery import shared_task
from django.conf import settings
from django.core import serializers
from api.tool.log_tool import logging_exception
from social.models import UserFollow
from trans2es.type_info import get_type_info_map
from gaia.routers import thread_local
from rpc.all import get_rpc_remote_invoker


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.DBMW_SLAVE_DB_NAME)
def write_to_es(es_type, pk_list, configuration, use_batch_query_set=False):
    pk_list = list(frozenset(pk_list))
    type_info_map = get_type_info_map()
    type_info = type_info_map[es_type]
    type_info.insert_table_by_pk_list(
        index_prefix=settings.ES_INDEX_PREFIX,
        pk_list=pk_list,
        use_batch_query_set=use_batch_query_set
    )


# TODO: ugly patch
def multitopic_es_trigger(es_type, pk):
    # es_type : problem or question
    assert es_type in ['topic', 'question']
    write_to_es(es_type=es_type, pk_list=[pk], configuration=None)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.DBMW_SLAVE_DB_NAME)
def user_follow_sync(ids):
    """

    :param ids:
    :return:
    """
    r = get_rpc_remote_invoker()
    queryset = UserFollow.objects.filter(pk__in=ids)
    data = serializers.serialize('python', queryset)
    print(data)
    items = []
    for item in data:
        obj = item['fields']
        obj['user_id'] = obj.pop('user')
        obj['follow_id'] = obj.pop('follow')
        obj['update_time'] = obj['update_time'].strftime("%Y-%m-%d %H:%M:%S") if obj['update_time'] else None
        obj['id'] = item['pk']
        items.append(obj)
    r['mimas/sync/user_follow'](items=items).unwrap()
