package com.framework.cache.helper.core.redisstore;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import com.framework.cache.helper.anotation.Cache;
import com.framework.cache.helper.core.SpringContextUtil;
import com.framework.cache.helper.core.Store;
import com.framework.cache.helper.util.SerializableUtils;

/**
 * @author 朱小杰
 * @since 2016年11月9日 下午5:14:29
 * 版本 1.0<br>
 * @see [说明这个类的作用]  
 */
public class RedisHelper implements Store{

	private MiniJedis miniJedis;
	
	private volatile static RedisHelper instance;
	

	@Override
	public Object cache(ProceedingJoinPoint point,Cache annotation,String key,Class<?> returnType,Object[] parameters) throws Throwable {
		if(String.class.equals(returnType)){
        	//存储string类型在redis中
    		String text = miniJedis.get(key);
    		if(null != text){
    			return text;
    		}else{
    			Object object = point.proceed(parameters);
    			if(-1 == annotation.cacheTime()){
    				miniJedis.set(key, object.toString());
    			}else{
    				miniJedis.set(key, object.toString(), annotation.cacheTime());
    			}
    			return object;
    		}
    	}else{
    		//序列化
    		byte[] bs = miniJedis.get(key.getBytes());
    		if(bs != null && bs.length > 0){
    			return SerializableUtils.deSerializ(bs, returnType);
    		}else{
    			Object object = point.proceed(parameters);
    			byte[] buf = SerializableUtils.serializ(object);
    			if(-1 == annotation.cacheTime()){
    				miniJedis.set(key.getBytes(), buf);
    			}else{
    				miniJedis.set(key.getBytes(), buf, annotation.cacheTime());
    			}
    			return object;
    		}
    	}
	}

	private RedisHelper(){
		ApplicationContext context = SpringContextUtil.getApplicationContext();
		if(context == null){
			throw new RuntimeException("获取org.springframework.context.ApplicationContext失败，spring没有加载完，请在spring加载完之后调用");
		}
		try {
			miniJedis = context.getBean(MiniJedis.class);
		} catch (BeansException e) {
			throw new NullPointerException("使用redis作为缓存，但是未在spring中找到redis.clients.util.Pool<T>的实例，其接口类型有redis.clients.jedis.ShardedJedisPool,与redis.clients.jedis.JedisPool请注入两个中的一个实例");
		}if(miniJedis == null){
			throw new NullPointerException("使用redis作为缓存，但是未在spring中找到redis.clients.util.Pool<T>的实例，其接口类型有redis.clients.jedis.ShardedJedisPool,与redis.clients.jedis.JedisPool请注入两个中的一个实例");
		}
	}

	/**
	 * @see [说明这个方法]
	 * @return
	 * @since 2016年11月9日 下午5:52:13
	 */
	public static RedisHelper getInstance() {
		if(instance == null){
			synchronized (RedisHelper.class) {
				if(instance == null){
					instance = new RedisHelper();
				}
			}
		}else{
		}
		return instance;
	}
	
}
