package com.eactive.eai.agent.encryption;

import org.springframework.stereotype.Component;

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.property.PropManager;
import com.eactive.eai.common.server.Keys;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;

@Component
public class EncryptionManager implements Lifecycle {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static final String GROUP_NAME = "ENCRYPTION";

	private String encryptYN = "";
	private boolean started;
	private LifecycleSupport lifecycle = new LifecycleSupport(this);

	private EncryptionManager() {

	}

	public static EncryptionManager getInstance() {
		return ApplicationContextProvider.getContext().getBean(EncryptionManager.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 Exception {
		encryptYN = "";
		encryptYN = PropManager.getInstance().getProperty(GROUP_NAME, System.getProperty(Keys.SERVER_KEY));
		if (encryptYN == null) {
			encryptYN = "N";
		} else {
			if (encryptYN.trim().length() == 0) {
				encryptYN = "N";
			}
		}

		logger.warn("EncryptionManager] init :: encryption YN [ " + encryptYN + " ]");
	}

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

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

		lifecycle.fireLifecycleEvent(STOPING_EVENT, this);

		encryptYN = null;
		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 String getEncryptYN() {
		return encryptYN;
	}
}
