# coding=utf-8
from _mysql import IntegrityError

from django.db.models import Q
from django.conf import settings

from api.models import Share
from hera.datatables import ShareDT
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 ..queries.share import ShareDQ

uri_pre = 'hera/'


@bind_context(uri_pre + 'share/edit')
def edit_share(ctx, share_id=None, share_info=None):
    """
    新增或者编辑文案分享配置
    :param ctx:
    :param share_id: share的id
    :param share_info: share的实体
    """
    if share_info is None:
        return None
    if share_id is None:
        try:
            share = Share.objects.create(**share_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            share = Share.objects.get(id=share_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in share_info.iteritems():
            setattr(share, k, v)
        share.save()
    return {"share_id": share.id}


@bind_context(uri_pre + 'share/get')
def get_share(ctx, share_id):
    """
    获取分享文案配置
    """
    if share_id is None:
        return None
    try:
        share = Share.objects.get(id=share_id)
    except IntegrityError:
        raise RPCIntegrityError
    share_data = to_dict(share)
    return share_data


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


@bind_context(uri_pre + 'share/list')
def share_datatable(ctx, req_data):
    dtobj = ShareDT(Share)
    return dtobj.process(req_data)


@bind_context(uri_pre + 'share/choices')
def share_choices(ctx, q='', page=1, num=30, initial=None):
    """
    :param ctx:
    :param num:
    :param page:
    :param q:查询关键字

    """
    page = int(page)
    num = int(num)
    if initial is not None:
        if isinstance(initial, (list, tuple)):
            qry = Q(id__in=initial)
        else:
            qry = Q(id=initial)
    else:
        qry = Q(id__contains=q) | Q(title__contains=q)
    query = Share.objects.using(settings.SLAVE_DB_NAME).filter(qry).order_by('-id')
    total_count = query.count()
    start_pos = (page - 1) * num
    start_pos = start_pos if start_pos >= 0 else 0
    results = [
        {
            'id': obj.id,
            'text': u'{}:{}'.format(
                obj.id, obj.title),
        } for obj in query[start_pos: start_pos + num]
        ]
    return {'total_count': total_count, 'results': results, 'page': page, 'num': num}
