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

from django.db import IntegrityError
from django.db.models import Q

from hera.queries.talos.filterword import FilterWordDQ
from rpc.decorators import bind_context
from rpc.exceptions import (RPCIntegrityError,
                            RPCNotFoundException)
from rpc.tool.dict_mixin import to_dict
from rpc.tool.log_tool import info_logger
from hera.datatables import FilterWordDT
from talos.models.report import FilterWord

__author__ = 'Zyy'

uri_pre = 'hera/filterword'


@bind_context(uri_pre + '/query')
def filterword_query(ctx, options):
    dqobj = FilterWordDQ()
    return dqobj.process(**options)


# no longer use
# @bind_context(uri_pre+'/list')
# def filterword_datatable(ctx, req_data):
#     dtobj = FilterWordDT(FilterWord)
#     return dtobj.process(req_data)


@bind_context(uri_pre+'/listupdate')
def filterword_listupdate(ctx, items):
    info = []
    for obj in items:
        filterwordinfo = FilterWord.objects.get(id=obj['id'])
        filterwordinfo.in_user_name = obj['in_user_name']
        filterwordinfo.in_topic_content = obj['in_topic_content']
        filterwordinfo.in_topic_reply = obj['in_topic_reply']
        filterwordinfo.in_topic_chat = obj['in_topic_chat']
        filterwordinfo.is_filter = obj['is_filter']
        filterwordinfo.save()
        info.append(obj['id'])
    return info


@bind_context(uri_pre+'/get')
def filterword_detail(ctx, filterword_id, options=None):
    try:
        filterword = FilterWord.objects.get(id=filterword_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    filterword_data = to_dict(filterword, **options)
    return filterword_data

@bind_context(uri_pre+'/edit')
def filterword_edit(ctx, filterword_id=None, filterword_info=None):
    if filterword_info is None:
        return None

    if filterword_id is None:
        try:
            filterword = FilterWord.objects.create(**filterword_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            filterword = FilterWord.objects.get(id=filterword_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in filterword_info.iteritems():
            setattr(filterword, k, v)
        filterword.save()

    return filterword.id


@bind_context(uri_pre + '/check')
def filterword_check(ctx, check_type, content):
    q = Q()
    for key in check_type:
        q |= Q(**{key: True})
    words = FilterWord.objects.filter(is_filter=True).filter(q).values_list('word', flat=True)
    result = []
    for word in words:
        if word in content and word not in result:
            result.append(word)
    return {
        'result': ','.join(result) if result else '无匹配敏感词',
    }
