# -*- 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
from search.utils.es import get_talos_es7_service


@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, es_config=None):
    if es_type in ["service", 'sku']:
        es_config = [get_talos_es7_service]

    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,
        es_config=es_config
    )


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.DBMW_SLAVE_DB_NAME)
def synchronize_nearbycity(pk_list):
    from django.conf import settings
    import json
    from api.models.city import TransactionNearbyCity
    import redis

    redis_client = redis.StrictRedis.from_url(settings.LBS_REDIS_URL)

    nearby_citys = TransactionNearbyCity.objects.all()

    city_dict = {}

    for item in nearby_citys:
        city = item.city.tag.id
        nearby_city = item.nearby_city.tag.id

        if city in city_dict.keys():
            tmp = city_dict[city]
            tmp.append(nearby_city)
            city_dict[city] = tmp
        else:
            city_dict[city] = [nearby_city]

    for key in city_dict.keys():
        redis_key = 'nearby_city:' + str(key)
        result = redis_client.set(redis_key, json.dumps(city_dict[key]))
        print(result)


# 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()
