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.UrlPatternBean;
import jp.co.headwaters.webappos.controller.utils.ControllerUtils;
import jp.co.headwaters.webappos.controller.utils.PropertyUtils;

public class UrlPatternCache implements Serializable {

	private static final long serialVersionUID = 2147854024936888300L;
	private static final UrlPatternCache _instance = new UrlPatternCache();
	private Map<String, UrlPatternBean> _map;

	private UrlPatternCache() {
		setUrlPatternMap(new HashMap<String, UrlPatternBean>());
	}

	public static UrlPatternCache getInstance() {
		return _instance;
	}

	public Map<String, UrlPatternBean> getUrlPatternMap() {
		return this._map;
	}

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

	public void load() throws FileNotFoundException, IOException, ClassNotFoundException {
		try (
				FileInputStream fis = new FileInputStream(getInputFile());
				ObjectInputStream ois = new ObjectInputStream(fis)) {
			setUrlPatternMap(((UrlPatternCache) ois.readObject()).getUrlPatternMap());
		}
	}

	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.URL_PATTERN_DAT_FILE_NAME);
		return new File(sb.toString());
	}
}
