# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import redis
from django.conf import settings


class _PoolMinx(object):
    pool = redis.ConnectionPool(**settings.REDIS['view'])
    client = redis.Redis(connection_pool=pool)


class DiaryPV(_PoolMinx):
    _prefix = 'diary_pv'

    def get_k(self, diary_id):
        k = '%s:%s' % (self._prefix, diary_id)
        return k

    def get(self, diary_id):
        k = self.get_k(diary_id)
        return self.client.get(k)

    def incrby(self, diary_id, num=1):
        k = self.get_k(diary_id)
        self.client.incrby(k, num)


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')
                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)


class _RedisProxy(object):
    """redis proxy add prefix automatically."""

    __connect_class = redis.StrictRedis
    __pool = redis.ConnectionPool(**settings.DEFAULT_REDIS)
    _client = __connect_class(connection_pool=__pool)

    # add methods those are need to be hacked here
    _hacked_methods = set([
        '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(_RedisProxy._client, name)

        if name in _RedisProxy._hacked_methods:
            def newfunc(k, *args, **kwargs):
                prefix = object.__getattribute__(self, 'prefix')
                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)


_redis_proxy = _RedisProxy.get_client
_live_redis_proxy = _LiveRedisProxy.get_client

# todo update in 7660 mimas 维护，不要再写入！不要再写入！不要再写入！  ******start*******
# _pool = redis.ConnectionPool(**settings.REDIS['vote_cache'])
# vote_cache = redis.StrictRedis(connection_pool=_pool)
# hot_in_24hrs_cache = _redis_proxy("hot_in_24hrs")
diary_heat_score_cache = _redis_proxy('diary_heat')  # todo 等待hera 迁移完成，才可

_pool = redis.ConnectionPool(**settings.TALOS_RPC_CACHE)
talos_rpc_service_model_cache = redis.StrictRedis(connection_pool=_pool) #  todo 等待hera 迁移完成，才可
# diary_index_data_cache = redis.StrictRedis(connection_pool=_pool)
# high_quality_user_cache = _redis_proxy('high_quality_users')

diary_pv_cache = DiaryPV()   # todo 7675 上线后可删
# take_sofa_diary_cache = _redis_proxy('take_sofa_diary')

# todo update in 7660 mimas 维护，不要再写入！不要再写入！不要再写入！  ******end*******

recommend_cache = _redis_proxy("recommend")
model_cache = _redis_proxy('model_c')
talos_tagrel_cache = _redis_proxy('tagrel')
sleep_user_cache = _redis_proxy('sleep_user')

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')
push_diary_cache = _redis_proxy('push_diary_cache')
hodgepodge_banner_cache = _redis_proxy('hodgepodge_banner')
