# encoding=utf-8
from __future__ import unicode_literals

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

from talos.models.live import ZhiboConfig
from hera.queries.talos.zhibo import ZhiboConfigDQ
from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from hera.queries.choice_query import choice_query
from hera.utils import model_edit
from talos.services.user import UserService

__author__ = 'wangshengguang'

uri_pre = 'hera/zhibo'


@bind_context(uri_pre + '/choices')
def zhibo_choices(ctx, q='', page=1, num=30, initial=None, group=None):
    page = int(page)
    num = int(num)

    default_using = getattr(settings, 'MIMAS_SLAVE_DB_NAME', '')
    query = choice_query(ZhiboConfig, ['id', 'description'], 'id', q, initial, using=default_using)
    # total_count = query.count()
    total_count = 0
    start_pos = (page - 1) * num
    start_pos = start_pos if start_pos >= 0 else 0
    results = [{
        'id': u.id,
        'text': u'{}:{}'.format(u.id, UserService.get_user_by_user_id(u.anchor_user_id).nickname),
    } for u in query[start_pos: start_pos + num]]
    return {'total_count': total_count, 'results': results, 'page': page, 'num': num}


@bind_context(uri_pre + '/list')
def zhibo_list(ctx, options):
    dtobj = ZhiboConfigDQ()
    return dtobj.process(**options)


@bind_context(uri_pre + '/get')
def zhibo_detail(ctx, zhibo_id, options=None):
    try:
        zhibo_info = ZhiboConfig.objects.get(id=zhibo_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    data = to_dict(zhibo_info, **options)
    data['anchor_user'] = data['anchor_user_id']
    return data


@bind_context(uri_pre + '/modify')
def zhibo_modify(ctx, zhibo_id=None, zhibo_info=None):
    if zhibo_info is None:
        return None
    if zhibo_id:
        zhibo_info['id'] = zhibo_id
    res = {'time_conflict': False}
    zhibo_info['anchor_user_id'] = zhibo_info.pop('anchor_user')
    zhibo_obj = ZhiboConfig(**zhibo_info)
    if zhibo_obj.is_online and time_conflict(zhibo_obj):
        res['time_conflict'] = True
        return res

    zhibo_obj = model_edit(ZhiboConfig, zhibo_id, zhibo_info)
    res['zhibo_id'] = zhibo_obj.id
    return res


@bind_context(uri_pre + '/listupdate')
def zhibo_listupdate(ctx, items):
    res = {'time_conflict': False, 'info': []}
    wait_online = []
    # 先下线后上线
    for obj in items:
        zhibo = ZhiboConfig.objects.get(pk=obj['id'])
        if obj['is_online']:
            wait_online.append(zhibo)
        else:
            zhibo.is_online = False
            zhibo.save()
            res['info'].append(obj['id'])
    for zhibo_obj in wait_online:
        if time_conflict(zhibo_obj):
            res['time_conflict'] = True
            return res
        zhibo_obj.is_online = True
        zhibo_obj.save()
        res['info'].append(zhibo_obj.id)
    return res


def time_conflict(zhibo_obj):
    # 允许有多场直播预告，不进行检测
    return False
    rang = (zhibo_obj.start_time, zhibo_obj.end_time)
    qry = Q(is_online=True) & ((Q(start_time__range=rang) | Q(end_time__range=rang)) | Q(
        start_time__lte=zhibo_obj.start_time) & Q(end_time__gte=zhibo_obj.end_time))  # 我包含已存在或者已存在包含我
    query = ZhiboConfig.objects.filter(qry).exclude(id=zhibo_obj.id)
    if query.exists():
        return True
    return False
