package com.eactive.eai.custom.stderrorcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;

@Component
public class StdErrorCodeManager implements Lifecycle {

	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private LifecycleSupport lifecycle = new LifecycleSupport(this);
	private Map<String, StdErrorCodeVO> stdErrorCodes = new HashMap();
	private boolean started;

	@Autowired
	private StdErrorCodeDAO dao;

	public static StdErrorCodeManager getInstance() {
		return ApplicationContextProvider.getContext().getBean(StdErrorCodeManager.class);
	}

	public boolean isStarted() {
		return this.started;
	}

	public synchronized void reload() throws LifecycleException {
		logger.warn("reload StdErrorCodeManager ...");

		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.warn("reload StdErrorCodeManager finish...");
	}

	private void init() throws LifecycleException, Exception {
		try {
			this.stdErrorCodes = dao.getAllSTDErrorCode();
		} catch (DAOException e) {
			// throw new LifecycleException("RECEAICPM201");
			throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICPM201"));
		}
	}

	public void start() throws LifecycleException {
		if (started)
			throw new LifecycleException("RECEAICCM201");

		lifecycle.fireLifecycleEvent(STARTING_EVENT, this);

		try {
			init();
		} catch (Exception e) {
			throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICCM202"));
		}

		started = true;
		lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
	}

	public void stop() throws LifecycleException {
		if (!started)
			throw new LifecycleException("RECEAICCM203");

		lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
		started = false;
		logger.info("StdErrorCodeManager] It is stopped.");
		lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
	}

	public void addLifecycleListener(LifecycleListener listener) {
		lifecycle.addLifecycleListener(listener);
	}

	public LifecycleListener[] findLifecycleListeners() {
		return lifecycle.findLifecycleListeners();
	}

	public void removeLifecycleListener(LifecycleListener listener) {
		lifecycle.removeLifecycleListener(listener);
	}
	public StdErrorCodeVO getSTDErrorCode(String code) {
		return stdErrorCodes.get(code);
	}

	public String[] getAllKeyNames() {
		String[] names = this.stdErrorCodes.keySet().toArray(new String[0]);
		Arrays.sort(names);
		return names;
	}
}
