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

from django.db.models import Q
from django.db import IntegrityError
from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException, RPCIntegrityError
from rpc.tool.datatables import to_dict
from rpc.tool.log_tool import info_logger, logging_exception
from api.models import RecommendApp
from ..utils import remote_choices
from ..datatables import RecommendAppDT
from ..queries.recommendapp import RecommendAppDQ


uri_pre = 'hera/recommendapp'


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


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


@bind_context(uri_pre+'/list')
def recommendapp_datatable(ctx, req_data):
    dtobj = RecommendAppDT(RecommendApp)
    return dtobj.process(req_data)


@bind_context(uri_pre+'/get')
def recommendapp_detail(ctx, recommendapp_id, options=None):
    try:
        recommendapp = RecommendApp.objects.get(id=recommendapp_id)
    except:
        raise RPCNotFoundException

    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    recommendapp_data = to_dict(recommendapp, **options)
    return recommendapp_data


@bind_context(uri_pre+'/edit')
def recommendapp_edit(ctx, recommendapp_id=None, recommendapp_info=None):
    if recommendapp_info is None:
        return None
    if recommendapp_id is None:
        try:
            recommendapp = RecommendApp.objects.create(**recommendapp_info)
        except IntegrityError:
            logging_exception()
            raise RPCIntegrityError
    else:
        try:
            recommendapp = RecommendApp.objects.get(id=recommendapp_id)
        except:
            logging_exception()
            raise RPCNotFoundException
        for k, v in recommendapp_info.iteritems():
            setattr(recommendapp, k, v)
        recommendapp.save()

    return recommendapp.id
