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


class _UserTaskRedisProxy(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', 'get', 'setex', 'hget', 'hset', 'hincrby', 'hdel', 'hgetall',
        'smembers', 'sadd', 'incr', 'delete', 'expire', 'decr',
        'lpush', 'lrange', 'lrem', 'llen', 'sadd', 'srem', 'scard',
        'sismember', 'rpop', 'keys', 'rpush', 'hmget', 'exists'
    ]

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

        if name in _UserTaskRedisProxy._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)


_task_redis_proxy = _UserTaskRedisProxy.get_client
user_task_cache = _task_redis_proxy('user_task_center')