# -*- coding: UTF-8 -*-
import redis
from django.conf import settings


class _LiveRedisProxy(object):
    """redis proxy add prefix automatically."""
    __connect_class = redis.StrictRedis
    __pool = redis.ConnectionPool(**settings.LIVE_REDIS)
    _client = __connect_class(connection_pool=__pool)

    # add methods those are need to be hacked here
    _hacked_methods = [
        'set', 'get', 'setex', 'hget', 'hset', 'hincrby', 'hdel', 'hgetall',
        'smembers', 'sadd', 'incr', 'delete', 'expire', 'decr',
        'lpush', 'lrange', 'lrem', 'llen', 'sadd', 'srem', 'scard',
        'sismember', 'rpop', 'keys', 'rpush'
    ]

    def __getattribute__(self, name):
        attr = getattr(_LiveRedisProxy._client, name)

        if name in _LiveRedisProxy._hacked_methods:
            def newfunc(k, *args, **kwargs):
                prefix = object.__getattribute__(self, 'prefix')
                if isinstance(k, list):
                    k = [prefix + ':' + str(i) for i in k]
                else:
                    k = prefix + ':' + k
                result = attr(k, *args, **kwargs)
                return result

            return newfunc

        return attr

    def __init__(self, prefix):
        self.prefix = prefix

    @classmethod
    def get_client(cls, prefix=''):
        return cls(prefix)


_live_redis_proxy = _LiveRedisProxy.get_client
_pool = redis.ConnectionPool(**settings.REDIS['vote_cache'])
vote_cache = redis.StrictRedis(connection_pool=_pool)

live_view_num_cache = _live_redis_proxy('live_view_num_cache')
live_msg_cache = _live_redis_proxy('live_msg_cache')
live_view_sum_cache = _live_redis_proxy('live_view_sum')
live_view_max_cache = _live_redis_proxy('live_view_max')
live_user_msg_check = _live_redis_proxy('live_user_msg_check')
live_user_enter_time_cache = _live_redis_proxy('live_user_enter_time')
live_user_enter_check = _live_redis_proxy('live_user_enter_check')
live_other_kv_cache = _live_redis_proxy('live_other_kv_cache')
live_fake_vote_cache = _live_redis_proxy('live_fake_vote_cache')
live_fake_comment_cache = _live_redis_proxy('live_fake_comment_cache')
live_fake_comment_turns_cache = _live_redis_proxy("live_fake_comment_turns")
live_cache = _live_redis_proxy('live_cache')
live_robot_ratelimit_cache = _live_redis_proxy("live_robot_ratelimit_cache")