package com.engine.kq.wfset.attendance.framework;

import java.util.ArrayList;
import java.util.List;
import weaver.general.BaseBean;
import weaver.general.StaticObj;

/**
 * 
 * @author wcd
 * @version 1.0 2015-10-16
 */
public abstract class BaseCache<T> extends BaseBean {
	protected StaticObj staticobj = null;
	protected int current_index = -1;
	protected List<T> list = null;
	protected static Object lock = new Object();
	
	protected String cacheName;
	
	public BaseCache(String name) {
		this.cacheName = name;
		this.staticobj = StaticObj.getInstance();
		
		this.init();
	}
	
	@SuppressWarnings("unchecked")
	private void init() {
		try{
			synchronized (lock) {
				if (staticobj.getObject(cacheName) == null) setValue();
				list = (List<T>) (staticobj.getRecordFromObj(cacheName, "list"));
				if (list == null) setValue();
			}
		} catch(Exception e){
			writeLog(e);
		}
	}
	
	private void setValue() throws Exception {
		if(list != null) 
			list.clear();
		else 
			list = new ArrayList<T>();

		list.addAll(findResults());
		
		staticobj.putRecordToObj(cacheName, "list", list);
	}
	
	protected abstract List<T> findResults(); 
	
	public List<T> getResult() {
		return list == null ? new ArrayList<T>() : list;
	}
	
	public int length() {
		return list == null ? 0 : list.size();
	}
	
	public void remove() {
		if (staticobj.getObject(cacheName) != null)
			staticobj.removeObject(cacheName);
	}

}
