package com.gci.boot.common.util;

import org.springframework.beans.BeansException;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public final class CacheUtil implements ApplicationContextAware{

	private static CacheManager cacheManager;

	public static <T> T get(String cacheName, String key, Class<T> cls) {
		Cache cache = cacheManager.getCache(cacheName);
		Cache.ValueWrapper valueWrapper = cache.get(key);
		if(valueWrapper == null || valueWrapper.get() == null){
			return null;
		}
		return cls.cast(valueWrapper.get());
	}

	public static Object get(String cacheName, String key) {
		Cache cache = cacheManager.getCache(cacheName);
		Cache.ValueWrapper valueWrapper = cache.get(key);
		return valueWrapper.get();
	}

	public static void put(String cacheName, String key, Object value) {
		Cache cache = cacheManager.getCache(cacheName);
		cache.put(key, value);
	}

	public static void evit(String cacheName, String key) {
		Cache cache = cacheManager.getCache(cacheName);
		cache.evict(key);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		CacheUtil.cacheManager = applicationContext.getBean(CacheManager.class);
	}

}
