package com.gaowj.business.cache;



import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.springframework.cache.Cache;

import com.gaowj.business.SystemCacheBusiness;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.Page;

public class SystemCacheBusinessImpl implements SystemCacheBusiness {
	
	private org.springframework.cache.support.CompositeCacheManager cacheManager;
	
	public void setCacheManager(
			org.springframework.cache.support.CompositeCacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}



	@Override
	public void ClearAllCache() throws BusinessException {
		Collection<String>  collection = cacheManager.getCacheNames();
		for(String name:collection){
			Cache cache =  cacheManager.getCache(name);
			cache.clear();
		}
		

	}
	
	/**
	 *分页显示缓存信息
	 */
      public Page<Map<String, Object>> listCache(int pageNo, int pageSize, Map<String, Object> query){
    	  
    	List<Map<String, Object>> datas =  listCache();
    	try {
			listSort(datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	//计算起始记录
  		int pageStart = (pageNo - 1) * pageSize;
  		
  		//获取列表
  		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
  		//获取列表个数
  		int count = datas.size();
  		
  		//设置分页信息
  		int start = (pageNo - 1) * pageSize;
  		int end = 0;
  		if (start + pageSize > count) 
  	       end = count; 
  	    else 
  		   end = start + pageSize;
  		
  		for (int i = start; i < end; i++) {
  			items.add(datas.get(i));
  		}
  		//
  		
  		//创建分页对象
  		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
  		page.setStart(pageStart);
  		page.setLimit(pageSize);
  		page.setCount(count);
  		page.setItems(items);

  		return page;
      }



	@Override
	public List<Map<String, Object>> listCache() throws BusinessException {
		List<Map<String, Object>> listCache = new ArrayList<Map<String, Object>>();
		Collection<String>  collection = cacheManager.getCacheNames();
		for(String name:collection){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("NAME", name);
			if(cacheManager.getCache(name).getNativeCache() instanceof Ehcache) {
				Ehcache ehcache = (Ehcache) cacheManager.getCache(name).getNativeCache();
				m.put("STATUS", ehcache.getCacheManager().getStatus().toString());
				m.put("MAXELEMENTS", ehcache.getCacheConfiguration().getMaxElementsInMemory());
				m.put("ETERNAL", ehcache.getCacheConfiguration().isEternal());
				m.put("TIMETOIDLESECONDS", ehcache.getCacheConfiguration().getTimeToIdleSeconds());
				m.put("TIMETOLIVESECONDS", ehcache.getCacheConfiguration().getTimeToLiveSeconds());
				m.put("OVERFLOWTODISK", ehcache.getCacheConfiguration().isOverflowToDisk());
				m.put("MAXELEMENTSONDISK", ehcache.getCacheConfiguration().getMaxElementsOnDisk());
				m.put("DISKPERSISTENT", ehcache.getCacheConfiguration().isDiskPersistent());
				m.put("DISKEXPIRYTHREADINTERVALSECONDS", ehcache.getCacheConfiguration().getDiskExpiryThreadIntervalSeconds());
				m.put("MEMORYSTOREEVICTIONPOLICY", ehcache.getCacheConfiguration().getMemoryStoreEvictionPolicy().toString());
				if(ehcache.getCacheManager().getStatus().equals(ehcache.getCacheManager().getStatus().STATUS_ALIVE))m.put("SIZE", ehcache.getSize());
				m.put("CACHETYPE","ehcache-2.8.3");
			}
			listCache.add(m);
		}
		return listCache;
	}
	
	
	/**
	 *分页显示缓存键信息
	 */
      public Page<Map<String, Object>> listCacheKey(int pageNo, int pageSize, Map<String, Object> query){
    	  
    	List<Map<String, Object>> datas =  listCacheKey((String)query.get("NAME"));

    	//计算起始记录
  		int pageStart = (pageNo - 1) * pageSize;
  		
  		//获取列表
  		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
  		//获取列表个数
  		int count = datas.size();
  		
  		//设置分页信息
  		int start = (pageNo - 1) * pageSize;
  		int end = 0;
  		if (start + pageSize > count) 
  	       end = count; 
  	    else 
  		   end = start + pageSize;
  		
  		for (int i = start; i < end; i++) {
  			items.add(datas.get(i));
  		}
  		//
  		
  		//创建分页对象
  		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
  		page.setStart(pageStart);
  		page.setLimit(pageSize);
  		page.setCount(count);
  		page.setItems(items);

  		return page;
      }


	@Override
	public List<Map<String, Object>> listCacheKey(String cacheName) throws BusinessException {
		List<Map<String, Object>> listCacheKey = new ArrayList<Map<String, Object>>();
		DateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(cacheManager.getCache(cacheName).getNativeCache() instanceof Ehcache) {
			Ehcache ehcache = (Ehcache) cacheManager.getCache(cacheName).getNativeCache();
			if(ehcache.getCacheManager().getStatus().equals(ehcache.getCacheManager().getStatus().STATUS_ALIVE)){
			for(Object key:ehcache.getKeys()){
				Map<String, Object> data = new HashMap<String,Object>();
				Element ele =  ehcache.get(key);
				if(ele == null || ele.getValue()==null)continue;
				Object obj = ele.getObjectValue();
				if(obj instanceof Page){
					Page obj_item = (Page) obj;
					obj = obj_item.getItems().toString();
				}
				data.put("KEYID", key);
				data.put("VALUE", obj);
				data.put("CREATIONTIME", sf.format(ele.getCreationTime()));
				data.put("LASTACCESSTIME", sf.format(ele.getLastAccessTime()));
				data.put("EXPIRATIONTIME", sf.format(ele.getExpirationTime()));
				data.put("LASTUPDATETIME", sf.format(ele.getLastUpdateTime()));
				data.put("HITCOUNT", ele.getHitCount());
				data.put("TIMETOLIVE", ele.getTimeToLive());
				data.put("TIMETOIDLE", ele.getTimeToIdle());
				listCacheKey.add(data);
			}
			}
		}
		
		return listCacheKey;
	}


    /**
     * 已实现shutdown,暂时不使用
     */
	@Override
	public boolean shutdownCache(String cacheName)
			throws BusinessException {
//		if(cacheManager.getCache(cacheName).getNativeCache() instanceof Ehcache) {
//			Ehcache ehcache = (Ehcache) cacheManager.getCache(cacheName).getNativeCache();
//			ehcache.getCacheManager().shutdown();
//			return true;
//		}
		return false;
	}



	@Override
	public boolean removeCache(String cacheName, String Key)
			throws BusinessException {
		if(cacheManager.getCache(cacheName).getNativeCache() instanceof Ehcache) {
			Ehcache ehcache = (Ehcache) cacheManager.getCache(cacheName).getNativeCache();
			return ehcache.remove(Key);	
		}
		return false;
	}



    /**
     * 未实现shutdown后重启
     */
	@Override
	public boolean createCache(String cacheName) throws BusinessException {
//		Collection<String>  collection = cacheManager.getCacheNames();
//		for(String name:collection){
//			Map<String, Object> m = new HashMap<String, Object>();
//			m.put("NAME", name);
//			if(cacheManager.getCache(name).getNativeCache() instanceof Ehcache) {
//				Ehcache ehcache = (Ehcache) cacheManager.getCache(name).getNativeCache();
//				URL secondCacheConfiguration = this.getClass().getResource("/ehcache.xml");
//				CacheManager encacheManager = ehcache.getCacheManager();
//				encacheManager = new CacheManager(secondCacheConfiguration);
 
//				Ehcache ehcache = (Ehcache) cacheManager.getCache(name).getNativeCache();
//				if(ehcache.getCacheManager().getStatus().equals(ehcache.getCacheManager().getStatus().STATUS_SHUTDOWN)){
//					ehcache.getCacheManager().clearAllStartingWith("");
//					ehcache.getCacheManager().clearAllStartingWith("ehcache");
//				}
//			}
//		}
		return true;
	}
	
	public void listSort(List<Map<String, Object>> resultList) throws Exception {
		// resultList是需要排序的list,其内放的是Map
		// 返回的结果集
		Collections.sort(resultList, new Comparator<Map<String, Object>>() {

			public int compare(Map<String, Object> o1, Map<String, Object> o2) {

				// o1,o2是list中的Map,可以在其内取得值,按其排序,此例为升序,s1和s2是排序字段值
				String s1 = (String) o1.get("NAME");
				String s2 = (String) o2.get("NAME");

				if (s1.compareTo(s2)>0) {
					return 1;
				} else {
					return -1;
				}
			}
		});

	}

}