
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', 'mset', 'setex', 'hget', 'hmget', '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):
                    if isinstance(k, list):
                        k = [self.prefix + ':' + i for i in k]
                    elif isinstance(k, dict):
                        k = {(self.prefix + ':' + k): v for k, v in k.items()}
                    else:
                        k = self.prefix + ':' + k
                    data = f(k, *args, **kwargs)
                    # bug fix for py35, json.loads does accept bytes!
                    if type(data) == bytes:
                        try:
                            data = data.decode()
                        except Exception:
                            pass
                    return data
                return wrapper
            return f


vote_cache = RedisWrapper('vote_cache', settings.REDIS['vote_cache'])
answer_cache = RedisWrapper('answer_cache', settings.REDIS['answer_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数据池
quality_question_cache = RedisWrapper("quality_question_cache", settings.REDIS["high_quality_question_cache"])  # 异性评论缓存
diary_record_cache = RedisWrapper("diary_record_cache", settings.REDIS["default"])
