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

from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from django.db import transaction
from gm_types.gaia import SEARCH_KEYWORDS_POSITION, SEARCH_KEYWORDS_TYPE, HOT_SEARCH_JUMP_TYPE
from gm_types.error import ERROR
from rpc.tool.dict_mixin import to_dict
from api.models import SearchKeyword, User, SearchActivity
from api.models.search import TopicAggregation
from rpc.exceptions import GaiaRPCFaultException


class SearchKeywordDB(DataBuilder):
    def getval_cities_name(self, obj):
        return [x.name for x in obj.cities.all()]

    def getval_regions_name(self, obj):
        return [x.name for x in obj.regions.all()]


@DB
class SearchKeywordDQ(DataSQLQuery):
    model = SearchKeyword
    data_model = SearchKeywordDB
    distinct = True

    @staticmethod
    def params_check(_type, jump_type):
        if _type == SEARCH_KEYWORDS_TYPE.NEW_WIKI and jump_type != HOT_SEARCH_JUMP_TYPE.NORMAL:
            raise GaiaRPCFaultException(
                error=ERROR.UNIVERSAL,
                message=u'百科tab,跳转类型目前只支持正常搜索',
                data=None)

    def create(self, **kwargs):
        cities = kwargs.pop('cities')
        regions = kwargs.pop('regions')
        if 'type' in kwargs.keys():
            kwargs['position'] = SEARCH_KEYWORDS_POSITION.HOT
            if self.model.objects.filter(keyword=kwargs['keyword'], type=kwargs['type'],
                                         position=SEARCH_KEYWORDS_POSITION.HOT).exists():
                raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'该词在此tab已配置,不能重复配置，如需增加地区请在原配置上添加', data=None)
            self.params_check(kwargs["type"], kwargs["jump_type"])

        else:
            kwargs['position'] = SEARCH_KEYWORDS_POSITION.DEFAULT
            if self.model.objects.filter(keyword=kwargs['keyword'], position=SEARCH_KEYWORDS_POSITION.DEFAULT).exists():
                raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'该词已配置,不能重复配置，如需增加地区请在原配置上添加', data=None)
        obj = self.model.objects.create(**kwargs)
        obj.cities = cities
        obj.regions = regions
        return to_dict(obj)

    def update(self, updates, **kwargs):
        _pk = kwargs.get("id", 0)
        search_keyword_obj = self.model.objects.get(pk=_pk)
        self.params_check(search_keyword_obj.type, updates.get("jump_type", HOT_SEARCH_JUMP_TYPE.NORMAL))

        return super(SearchKeywordDQ.sqlquery, self).update(updates, **kwargs)

class TopicAggregationDB(DataBuilder):
    def getval_aggregate_id(self, obj):
        return obj.aggregate_id.split(",")
@DB
class TopicAggregationDQ(DataSQLQuery):
    model = TopicAggregation
    data_model = TopicAggregationDB
    distinct = True

    def create(self, **kwargs):
        aggregate_id = kwargs.pop('aggregate_id', [])
        kwargs['aggregate_id'] = ','.join(aggregate_id)
        return to_dict(self.model.objects.create(**kwargs))

    def update(self, updates, **kwargs):
        is_delete = updates.pop('is_delete', False)
        if is_delete:
            qs = TopicAggregation.objects.filter(**kwargs)
            count = qs.count()
            qs.delete()
            return count

        count = 0
        aggregate_id = updates.pop('aggregate_id', [])
        if aggregate_id:
            updates['aggregate_id'] = ','.join(aggregate_id)

        with transaction.atomic(self.model.objects.db):
            for obj in self.model.objects.select_for_update().filter(**kwargs):
                count += 1
                for k, v in updates.items():
                    setattr(obj, k, v)
                obj.save()
        return count


class SearchActivityDB(DataBuilder):

    def getval_time_range(self, obj):
        start_time = obj.start_time
        end_time = obj.end_time
        return str(start_time.strftime("%Y-%m-%d %H:%M:%S")) + '--' + str(end_time.strftime("%Y-%m-%d %H:%M:%S"))


@DB
class SearchActivityDQ(DataSQLQuery):
    model = SearchActivity
    data_model = SearchActivityDB

    def filter_operator_id(self, srch_key, srch_val, regex=False):
        try:
            user_id = int(srch_val)
        except ValueError:
            return Q()
        return Q(operator_id=user_id)

    def update(self, updates, **kwargs):
        return super(SearchActivityDQ.sqlquery, self).update(updates, **kwargs)
