package jp.co.headwaters.webappos.controller.cache;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import jp.co.headwaters.webappos.controller.ControllerConstants;
import jp.co.headwaters.webappos.controller.cache.bean.ActionBean;
import jp.co.headwaters.webappos.controller.utils.ControllerUtils;
import jp.co.headwaters.webappos.controller.utils.PropertyUtils;

public class ActionCache implements Serializable {

	private static final long serialVersionUID = 5105521411185230916L;

	private static final ActionCache _instance = new ActionCache();
	private Map<String, ActionBean> _map;

	private ActionCache() {
		setActionMap(new HashMap<String, ActionBean>());
	}

	public static ActionCache getInstance() {
		return _instance;
	}

	public Map<String, ActionBean> getActionMap() {
		return this._map;
	}

	public void setActionMap(Map<String, ActionBean> map) {
		this._map = map;
	}

	public void load() throws FileNotFoundException, IOException, ClassNotFoundException {
		try (
				FileInputStream fis = new FileInputStream(getInputFile());
				ObjectInputStream ois = new ObjectInputStream(fis)) {
			setActionMap(((ActionCache) ois.readObject()).getActionMap());
		}
	}

	private static File getInputFile() {
		StringBuilder sb = new StringBuilder();
		sb.append(PropertyUtils.getProperty(ControllerConstants.PROPERTY_KEY_WEBAPPS_PATH));
		if (!sb.toString().endsWith(ControllerUtils.getFileSparator())) {
			sb.append(ControllerUtils.getFileSparator());
		}
		sb.append(ControllerConstants.WEBAPPS_DAT_DIR);
		sb.append(ControllerUtils.getFileSparator());
		sb.append(ControllerConstants.ACTION_DAT_FILE_NAME);
		return new File(sb.toString());
	}
}
