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

from rpc.decorators import bind_context
from rpc.exceptions import (RPCPermissionDeniedException, RPCIntegrityError,
    RPCNotFoundException)
from rpc.tool.dict_mixin import to_dict
from api.models import UserBlackList
from ..utils import remote_choices
from ..datatables import BlackListDT

from rpc.tool.log_tool import info_logger


uri_pre = 'hera/blacklist'


@bind_context(uri_pre+'/choices')
def blacklist_choices(ctx, q='', page=1, num=30, initial=None):
    src_map = {'id': 'id', 'text': 'name'}
    if initial is None:
        qry_item = {'key': 'name', 'val': q}
        fetch_seleted = False
    else:
        qry_item = {'key': 'id', 'val': initial}
        fetch_seleted = True
    return remote_choices(UserBlackList, qry_item, fetch_seleted, page, num, src_map)


@bind_context(uri_pre+'/list')
def blacklist_datatable(ctx, req_data):
    dtobj = BlackListDT(UserBlackList)
    return dtobj.process(req_data)


@bind_context(uri_pre+'/get')
def blacklist_detail(ctx, blacklist_id, options=None):
    try:
        blacklist = UserBlackList.objects.get(id=blacklist_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    blacklist_data = to_dict(blacklist, **options)
    return blacklist_data


@bind_context(uri_pre+'/edit')
def blacklist_edit(ctx, blacklist_id=None, blacklist_info=None):
    if blacklist_info is None:
        return None

    if blacklist_id is None:
        try:
            blacklist = UserBlackList.objects.create(**blacklist_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            blacklist = UserBlackList.objects.get(id=blacklist_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in blacklist_info.iteritems():
            setattr(blacklist, k, v)
        blacklist.save()
    return blacklist.id
