# encoding=utf-8
from __future__ import unicode_literals

from django.db.models import Q

from api.models import ServiceReserve
from hera.queries.servicereserve import ServiceReserveDQ
from hera.utils import check_operate, operate_business
from rpc.decorators import bind_context

from ..datatables import ServiceReserveDT

uri_pre = 'hera/servicereserve'


@bind_context(uri_pre + '/list')
def servicereserve_datatable(ctx, req_data):
    dtobj = ServiceReserveDT(ServiceReserve)
    return dtobj.process(req_data, ['service__name', 'user__last_name'])


@bind_context(uri_pre + '/query')
def servicereserve_query(ctx, options):
    if check_operate(ctx.session.user_id):
        business_ids = operate_business(ctx.session.user_id)
        init_q = Q(service__doctor__business_partener__in=business_ids)
    else:
        init_q = None
    dqobj = ServiceReserveDQ(init_q=init_q)
    if options.get('search', None):
        if options.get('search', None).get('fields', None):
            if 'count' in options.get('search', None).get('fields', None):
                options.get('search', None).get('fields', None).remove('count')
    return dqobj.process(**options)
