
import redis
from django.conf import settings


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

    def __init__(self, prefix, conf):
        self.prefix = prefix
        self.__pool = redis.ConnectionPool(**conf)
        self.redis = redis.StrictRedis(connection_pool=self.__pool)

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

    def __getattribute__(self, name):
        """
        redis method hack.
        :param name:
        :return:
        """
        try:
            return super(RedisWrapper, self).__getattribute__(name)
        except AttributeError:
            f = getattr(self.redis,  name)
            if name in RedisWrapper._hacked_methods:
                def wrapper(k, *args, **kwargs):
                    k = self.prefix + ':' + k
                    data = f(k, *args, **kwargs)
                    # bug fix for py35, json.loads does accept bytes!
                    if type(data) == bytes: 
                        data = data.decode()
                    return data
                return wrapper
            return f


vote_cache = RedisWrapper('vote_cache', settings.REDIS['vote_cache'])
answer_sort_cache = RedisWrapper('answer_sort_cache', settings.REDIS['answer_sort_cache'])
high_quality_question_cache = RedisWrapper('high_quality_question_cache', settings.REDIS['high_quality_question_cache'])
question_inviter_cache = RedisWrapper("question_inviter_cache", settings.REDIS["default"])

complains_question_cache = RedisWrapper("complains_question_cache", settings.REDIS["default"])  # 吐槽小程序问题id数据池