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


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

    def __init__(self, conf):
        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',
        'hmget', 'hmset'
    ]

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


personalize_push_cache = RedisWrapper(settings.DEMETER_PUSH_REDIS)
doris_ctr_cache = RedisWrapper(settings.DORIS_REDIS)
