package com.eactive.eai.common.b2bservice;

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 B2BServiceManager implements Lifecycle {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

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

	@Autowired
	private B2BServiceDAO b2bServiceDAO;

	public static synchronized B2BServiceManager getInstance() {
		return ApplicationContextProvider.getContext().getBean(B2BServiceManager.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 {
		b2bsMsgs = null;
		b2bsMsgs = b2bServiceDAO.getAllB2BServices();
	}

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

	public synchronized void reload(String b2bExtnlInstiCd) throws Exception {
		if (logger.isWarn()) {
			logger.warn("B2BServiceManager] reload Started ...");
		}
		Map<String, B2BServiceVO> map = b2bServiceDAO.getB2BService(b2bExtnlInstiCd);
		if (map != null) {
			for (Map.Entry<String, B2BServiceVO> entry : map.entrySet()) {
				String key = entry.getKey();
				B2BServiceVO vo = entry.getValue();
				if ("1".equals(vo.getUseYn())) {
					b2bsMsgs.put(key, vo);
				} else {
					b2bsMsgs.remove(key);
					logger.warn("B2BServiceManager] reload key[" + key + "] useYn[0] removed");
				}
			}
		}

		if (logger.isWarn()) {
			logger.warn("B2BServiceManager] reload finished ...");
		}
	}

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

		lifecycle.fireLifecycleEvent(STOPING_EVENT, this);

		b2bsMsgs.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 B2BServiceVO getB2BServiceVO(String b2bExtnlInstiCd, int svcPssSeq) {
		String key = b2bExtnlInstiCd + svcPssSeq;
		return getB2BServiceVO(key);
	}

	public B2BServiceVO getB2BServiceVO(String key) {
		B2BServiceVO aMsg = b2bsMsgs.get(key);
		if (aMsg != null) {
			try {
				return (B2BServiceVO) ObjectUtil.deepCopy(aMsg);
			} catch (Exception e) {
				throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICMM204"));
			}
		} else {
			return aMsg;
		}
	}

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

	public void setB2BServiceVO(String code, B2BServiceVO msg) {
		b2bsMsgs.put(code, msg);
	}

	// db update 필요
	public void updateB2BServiceVO(String b2bExtnlInstiCd, int svcPssSeq, B2BServiceVO msg) {
		String key = b2bExtnlInstiCd + svcPssSeq;
		b2bsMsgs.put(key, msg);
	}

	public void removeB2BServiceVO(String b2bExtnlInstiCd, int svcPssSeq, B2BServiceVO msg) {
		String key = b2bExtnlInstiCd + svcPssSeq;
		b2bsMsgs.remove(key);
	}

	public void removeB2BServiceVO(String key) {
		b2bsMsgs.remove(key);
	}

}
