package com.eactive.eai.common.message;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
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;
import com.eactive.eai.common.util.ObjectUtil;

@Component
public class EAIMessageManager implements Lifecycle {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

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

	@Autowired
	EAIMessageDAO eaiMessageDAO;

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

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

		lifecycle.fireLifecycleEvent(STARTING_EVENT, this);

		try {
			init();
		} catch (Exception e) {
			throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICMM202"));
		}
		started = true;
		lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
	}

	private void init() throws DAOException {
		eaiMsgs = eaiMessageDAO.getAllEAIMessages();
	}

	public synchronized void reload() throws Exception {
		if (logger.isWarn()) {
			logger.warn("EAIMessageManager] reload all Started ...");
		}
		init();
		if (logger.isWarn()) {
			logger.warn("EAIMessageManager] reload all finished ...");
		}
	}

	public synchronized void reload(String keyName) throws Exception {
		EAIMessage msg = eaiMessageDAO.getEAIMessagesByCode(keyName);
		if (msg != null) {
			if ("1".equals(msg.getUseYn())) {
				eaiMsgs.put(keyName, msg);
			} else {
				eaiMsgs.remove(keyName);
				logger.warn("EAIMessageManager] reload key[" + keyName + "] useYn[0] removed");
			}
		} else {
			throw new Exception("EAIMessage not found in Database : key[" + keyName + "]");
		}
	}

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

		lifecycle.fireLifecycleEvent(STOPING_EVENT, this);

		eaiMsgs.clear();

		started = false;
		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 boolean isStarted() {
		return this.started;
	}

	public EAIMessage getEAIMessage(String eaiSvcCd) throws Exception {
		EAIMessage aMsg = eaiMsgs.get(eaiSvcCd);
		if (aMsg != null) {
			try {
				return (EAIMessage) ObjectUtil.deepCopy(aMsg);
			} catch (Exception e) {
				throw new Exception(ExceptionUtil.getErrorCode(e, "RECEAICMM204"), e);
			}
		} else {
			return aMsg;
		}
	}

	public String[] getAllEAISvcCd() {
		Iterator<String> it = this.eaiMsgs.keySet().iterator();
		String[] svcCd = new String[this.eaiMsgs.size()];
		for (int i = 0; it.hasNext(); i++) {
			svcCd[i] = it.next();
			if (svcCd[i] == null)
				svcCd[i] = "";
		}
		Arrays.sort(svcCd);
		return svcCd;
	}

	public void removeEAIMessage(String code) {
		eaiMsgs.remove(code);
	}
}
