# encoding=utf-8
from __future__ import unicode_literals

import random

from django.db import IntegrityError
from django.contrib.auth.models import User

from api import Person
from gaia import settings
from talos.models.live import LiveWhiteList
from api.tool.live_tool import get_or_create_channel_by_user_id
from api.tool.user_tool import filter_user_nick_name
from hera.queries.talos.zhubo import LiveWhiteListDQ
from rpc.cache import puppet_users_cache
from rpc.decorators import bind_context, bind
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from rpc.tool.log_tool import info_logger
from talos.manager.livemsg import LiveMsgManager

from talos.models.live import LiveChannel
from rpc.tool.error_code import gen, CODES


__author__ = 'Yang Zhou'

uri_pre = 'hera/zhubo'


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


@bind_context(uri_pre + '/get')
def zhubo_detail(ctx, zhubo_id, options=None):
    try:
        zhubo_info = LiveWhiteList.objects.get(id=zhubo_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    data = to_dict(zhubo_info, **options)
    data['user_name'] = data['user_id']
    return data


@bind_context(uri_pre + '/modify')
def zhubo_modify(ctx, zhubo_id=None, zhubo_info=None):
    if zhubo_id:
        zhubo_info['id'] = zhubo_id
    res = {}
    zhubo_info['user_id'] = zhubo_info.pop('user_name')
    # zhubo_obj = LiveWhiteList(**zhubo_info)
    if zhubo_id is None:
        try:
            zhubo_obj = LiveWhiteList.objects.create(**zhubo_info)
            #  为主播创建一个直播渠道
            get_or_create_channel_by_user_id(zhubo_obj.user_id)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            zhubo_obj = LiveWhiteList.objects.get(id=zhubo_id)
            for k, v in zhubo_info.iteritems():
                setattr(zhubo_obj, k, v)
            zhubo_obj.save()
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
    res['zhubo_id'] = zhubo_obj.id
    return res


@bind_context(uri_pre + '/send_msg')
def zhibo_send_msg(ctx, zhibo_user_id, puppet_user_id, send_msg):
    if puppet_user_id:
        puppet_user = User.objects.get(id=puppet_user_id)
    else:
        count = User.objects.filter(person__is_puppet=True).count()
        puppet_user = User.objects.filter(person__is_puppet=True)[random.randint(0, count-1)]
    zhibo_user = User.objects.get(id=zhibo_user_id)
    puppet_user.person_id = puppet_user.person.id.hex
    puppet_user.nickname = filter_user_nick_name(puppet_user)
    if not LiveMsgManager.check_msg_enable(puppet_user):
        gen(CODES.LIVE_MSG_TOO_FREQUENTLY)

    stream = LiveChannel.objects.get(person_id=zhibo_user.person.id.hex).now_stream
    if not stream:
        gen(CODES.LIVE_IS_NOT_FOUND)
    live_msg_manager = LiveMsgManager()
    live_msg_manager.add_send_msg(stream, puppet_user, send_msg, True)


@bind(uri_pre + '/get_puppet_user_ids')
def get_puppet_user_ids(num=1):
    """ 优先从缓存获取， 若没有获取到则走 DB 从库. """

    puppet_user_ids = []
    key = "puppet_user_ids_set"
    puppet_user_ids = puppet_users_cache.srandmember(key, num)

    if not puppet_user_ids:

        count = Person.objects.using(settings.SLAVE_DB_NAME).filter(is_puppet=True).count()
        start = random.randint(0, count-num)
        puppet_user_ids = Person.objects.using(settings.SLAVE_DB_NAME).filter(is_puppet=True).values_list('user_id', flat=True)[start: start+num]

    return [int(user_id) for user_id in puppet_user_ids]
