# -*- coding: UTF-8 -*-
from django.conf import settings
from live.models import LiveStream
from talos.cache.live import live_cache

from utils.cache import common_cache_wrapper


class LiveService(object):
    @classmethod
    def current_living_with_whitelist(cls, is_test=False):
        streams = LiveStream.get_current_streams(is_test=is_test)
        if getattr(settings, 'USE_LIVE_FLOATING_WHITELIST', True):
            floating_person_ids = cls.get_floating_person_ids()
            merchant_streams = [s for s in streams if s.channel.person_id in floating_person_ids]
        else:
            merchant_streams = streams
        return merchant_streams

    @classmethod
    def current_living_with_floating_config(cls, config_stream_id, is_test=False):
        streams = LiveStream.get_current_streams(is_test=is_test)
        for stream in streams:
            if stream.id == config_stream_id:
                return stream
        return None

    @classmethod
    @common_cache_wrapper('live_floating_person_ids')
    def get_floating_person_ids(cls):
        """获取能展示到悬浮窗的白名单person_ids"""
        res = live_cache.smembers('floating_person_ids')
        person_ids = {r.decode() for r in res}
        return person_ids


    @classmethod
    @common_cache_wrapper('live_has_living_now')
    def has_living_now(cls, is_test=False):
        streams = LiveStream.get_current_streams(is_test=is_test)
        res = streams.select_related(None).exists()
        return res