# coding=utf-8

from django.db import IntegrityError

from api.models.consult import ConsultWiki
from rpc.decorators import bind_context, bind
from hera.datatables import ConsultWikiDT
from rpc.exceptions import RPCNotFoundException, RPCIntegrityError
from rpc.tool.dict_mixin import to_dict
from rpc.tool.log_tool import info_logger
from api.tool.consult_tool import ConsultConfig
from ..queries.consultwiki import ConsultWikiDQ

consult_pre = 'hera/consult'


@bind(consult_pre + '/set_config')
def set_consult_config(config):
    ConsultConfig.set(config)


@bind(consult_pre + '/get_config')
def get_consult_config():
    return ConsultConfig.get()


@bind_context(consult_pre + '/wiki_query')
def consult_wiki_query(ctx, options):
    dqpbj = ConsultWikiDQ()
    return dqpbj.process(**options)


@bind_context(consult_pre + '/wiki_list')
def consult_wiki_datatable(request, req_data):
    dtobj = ConsultWikiDT(ConsultWiki)
    return dtobj.process(req_data)


@bind_context(consult_pre + '/wiki_get')
def consult_wiki_detail(ctx, id, options=None):
    try:
        consult_wki = ConsultWiki.objects.get(id=id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    data = to_dict(consult_wki, **options)
    return data


@bind_context(consult_pre + '/wiki_edit')
def consult_wiki_edit(ctx, id=None, consult_wiki_info=None):
    if consult_wiki_info is None:
        return None

    consult_wiki_info['wiki_id'] = consult_wiki_info.pop('wiki')
    if id is None:
        try:
            consult_wiki = ConsultWiki.objects.create(**consult_wiki_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            consult_wiki = ConsultWiki.objects.get(id=id)
            for k, v in consult_wiki_info.iteritems():
                setattr(consult_wiki, k, v)
            consult_wiki.save()
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException

    return consult_wiki.id


@bind_context(consult_pre + '/wiki_listupdate')
def consult_wiki_listupdate(ctx, items):
    info = []
    for obj in items:
        consult_wiki = ConsultWiki.objects.get(pk=obj['key'])
        consult_wiki.is_online = obj['is_online']
        consult_wiki.ordering = obj['ordering']
        consult_wiki.save()
        info.append(obj['key'])
    return info
