# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import datetime
import json
import time

from django.conf import settings
from django.db.models import Q
from gm_types.gaia import LIVE_MSG_TYPE

from talos.cache.base import live_msg_cache, live_user_enter_check
from talos.cache.base import live_user_msg_check
from talos.models.live import LiveMsg


class LiveMsgManager(object):
    def __init__(self):
        self.msg_cache = live_msg_cache

    @staticmethod
    def get_live_redis_key(id):
        return 'msg' + str(id)

    @staticmethod
    def get_live_like_redis_key(id):
        return 'live_like' + str(id)

    def get_user_send_msg(self, stream, msg_id, user):
        if settings.LIVE_MSG_REDIS_FLAG:
            return self._get_user_send_msg_redis(stream, msg_id, user)
        else:
            return self._get_user_send_msg_mysql(stream, msg_id, user)

    def _get_user_send_msg_redis(self, stream, msg_id, user):
        key = self.get_live_redis_key(stream.id)
        newest_id = self.msg_cache.llen(key)

        # id 为空 为第一次进入 直接返回无数据即可 或者消息id 等于最新的消息数量
        if msg_id == '' or str(msg_id) == str(newest_id):
            return {
                'news': [],
                'newest_id': newest_id,
                'audience_num': stream.channel.live_view_num,
                'title': stream.title
            }
        msg_id = int(msg_id)
        msgs = self.msg_cache.lrange(key, msg_id, newest_id)
        news = []
        for msg in msgs:
            msg = json.loads(msg)
            msg_id += 1
            if user and user.id == msg.get('user_id', 0):
                continue
            else:
                msg['id'] = msg_id
                if msg.get('user_id'):
                    del msg['user_id']
                news.append(msg)

        return {
            'news': news,
            'newest_id': newest_id,
            'audience_num': stream.live_view_num,
            'title': stream.title
        }

    @staticmethod
    def _get_user_send_msg_mysql(stream, msg_id, user):
        newest_msg = LiveMsg.objects.filter(stream=stream).order_by('-id').first()
        newest_id = newest_msg.id

        if msg_id == '':
            now = datetime.datetime.now()
            msgs = LiveMsg.objects.filter(stream=stream, created_time__gte=now)
        else:
            msgs = LiveMsg.objects.filter(stream=stream, id__gt=msg_id)

        if user:
            msgs = msgs.filter(~Q(person_id=user.person_id))

        msgs = msgs.order_by('-id')[:30]
        news = []
        for msg in msgs:
            news.append(msg.data())

        return {
            'news': news,
            'newest_id': newest_id,
            'audience_num': stream.channel.live_view_num,
            'title': stream.title
        }

    def add_enter_msg(self, stream, user):
        if not self.check_user_enter_enable(stream, user):
            return

        if settings.LIVE_MSG_REDIS_FLAG:
            self._add_enter_msg_redis(stream, user)
        else:
            self._add_enter_msg_mysql(stream, user)

    def _add_enter_msg_redis(self, stream, user):
        k = self.get_live_redis_key(stream.id)
        if stream.channel.person_id == user.person_id:
            msg = {
                'text': u'主播回来啦,马上恢复直播',
                'name': '',
                'type': LIVE_MSG_TYPE.NOTIFI_MSG,
                'user_id': '0'
            }
            self.msg_cache.rpush(k, json.dumps(msg))
        else:
            msg = {
                'text': u'进入房间',
                'name': user.nickname,
                'type': LIVE_MSG_TYPE.ENTER_MSG,
                'user_id': '0'
            }
            self.msg_cache.rpush(k, json.dumps(msg))
            stream.set_first_user_enter_time_cache()

    @staticmethod
    def _add_enter_msg_mysql(stream, user):
        if stream.channel.person_id == user.person_id:
            msg = LiveMsg.objects.create(person_id=user.person_id, stream=stream, msg=u'主播回来啦,马上恢复直播',
                                         type=LIVE_MSG_TYPE.NOTIFI_MSG)
        else:
            msg = LiveMsg.objects.create(person_id=user.person_id, stream=stream, msg=u'进入房间',
                                         type=LIVE_MSG_TYPE.ENTER_MSG)
        return msg.data()

    def add_leave_msg(self, stream, user):
        if settings.LIVE_MSG_REDIS_FLAG:
            self._add_leave_msg_redis(stream, user)
        else:
            self._add_leave_msg_mysql(stream, user)

    @staticmethod
    def _add_leave_msg_mysql(stream, user):
        if stream.channel.person_id == user.person_id:
            LiveMsg.objects.create(person_id=user.person_id, stream=stream, msg=u'主播离开一会,不要走开哇',
                                   type=LIVE_MSG_TYPE.NOTIFI_MSG)

    def _add_leave_msg_redis(self, stream, user):
        k = self.get_live_redis_key(stream.id)
        if stream.channel.person_id == user.person_id:
            msg = {
                'text': u'主播离开一会,不要走开哇',
                'name': '',
                'type': LIVE_MSG_TYPE.NOTIFI_MSG,
                'user_id': 0
            }
            self.msg_cache.rpush(k, json.dumps(msg))

    def add_send_msg(self, stream, user, msg, is_vest_send=False, type=LIVE_MSG_TYPE.TEXT_MSG):
        if settings.LIVE_MSG_REDIS_FLAG:
            msg = self._add_send_msg_redis(stream, user, msg, is_vest_send, type)
        else:
            msg = self._add_send_msg_mysql(stream, user, msg, is_vest_send)
        return msg

    @staticmethod
    def _add_send_msg_mysql(stream, user, msg, is_vest_send=False):
        msg = LiveMsg.objects.create(person_id=user.person_id, stream=stream, msg=msg, is_vest_send=is_vest_send)
        return msg.data()

    def _add_send_msg_redis(self, stream, user, msg, is_vest_send=False, type=LIVE_MSG_TYPE.TEXT_MSG):
        self._add_send_msg_mysql(stream, user, msg, is_vest_send)
        msg = {
            'id': 0,  # 用来占位
            'text': msg,
            'name': user.nickname,
            'type': type,
            'user_id': user.id
        }
        key = self.get_live_redis_key(stream.id)
        self.msg_cache.rpush(key, json.dumps(msg))
        return msg

    def add_live_like_msg(self, stream, user, msg, type=LIVE_MSG_TYPE.TEXT_MSG):
        if settings.LIVE_MSG_REDIS_FLAG:
            msg = self._add_live_like_msg_redis(stream, user, msg, type)
        else:
            msg = self._add_send_msg_mysql(stream, user, msg)
        return msg

    def _add_live_like_msg_redis(self, stream, user, msg, type=LIVE_MSG_TYPE.TEXT_MSG):
        msg = {
            'id': 0,  # 用来占位
            'text': msg,
            'name': user.nickname,
            'type': type,
            'user_id': user.id
        }
        live_like_key = self.get_live_like_redis_key(stream.id)
        timestamp = int(time.time())
        time_key = str(timestamp)

        self.msg_cache.zadd(live_like_key, timestamp, time_key)
        key = self.get_live_redis_key(stream.id)
        self.msg_cache.rpush(key, json.dumps(msg))
        return msg

    @staticmethod
    def check_msg_enable(user):
        if settings.SEND_MSG_TIME == 0:
            return True

        if live_user_msg_check.get(str(user.id)):
            return False
        else:
            live_user_msg_check.setex(str(user.id), settings.SEND_MSG_TIME, settings.SEND_MSG_TIME)
            return True

    @staticmethod
    def user_enter_stream_key(stream, user):
        return str(stream.id) + ':' + str(user.id)

    @staticmethod
    def check_user_enter_enable(stream, user):
        if live_user_enter_check.get(LiveMsgManager.user_enter_stream_key(stream, user)):
            return False
        else:
            live_user_enter_check.setex(LiveMsgManager.user_enter_stream_key(stream, user), settings.ENTER_MSG_TIME,
                                        settings.ENTER_MSG_TIME)
            return True

    def clear_redis(self, stream_id):
        self.msg_cache.delete(self.get_live_redis_key(stream_id))
        self.msg_cache.delete(self.get_live_like_redis_key(stream_id))


