# coding=utf-8

import json
import random
try:
    import cPickle as pickle
except ImportError:
    import pickle

from rpc.cache import diary_cache
cache_mapping = {
#    index_key:                    (cache_define, seq_type, cache_key_prefix, expire_range)
    'func_filter_diary_index_mix': (diary_cache, 'json', 'func_filter_diary_index_mix', [240, 360]),
}

class CacheServer(object):

    def __init__(self, index_key, params=None):
        self.index_key = index_key
        try:
            self.c_server, self.c_type, self.c_prefix, self.time_range = cache_mapping.get(index_key)
        except Exception:
            raise Exception('index_key[%s] undefined' % index_key)
        self.cache_key = self.gen_cache_key(params, self.c_prefix)
        self.parser = pickle if self.c_type == 'pickle' else json

    def gen_cache_key(self, params, pre_key):
        '''
        生成缓存key
        '''
        params = params or {}
        key_list = []
        if pre_key:
            key_list.append(pre_key)
        key_list.extend([params[k] for k in sorted(params.keys())])
        return ':'.join(map(str, key_list))

    def get_result_from_cache(self):
        '''
        读取缓存
        '''
        cache_result = self.c_server.get(self.cache_key)
        if cache_result:
            return True, self.parser.loads(cache_result)
        else:
            return False, None

    def set_result_to_cache(self, data, expire_time=0, nx=True):
        '''
        写入缓存
        '''
        if expire_time == 0:
            expire_time = random.randint(self.time_range[0], self.time_range[1])
        return self.c_server.set(self.cache_key, self.parser.dumps(data), ex=expire_time, nx=nx)
    
