package com.eactive.eai.common;

import java.util.Iterator;
import java.util.Properties;

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.routing.ElinkESBProcessProxy;
import com.eactive.eai.common.routing.RouteKeys;
import com.eactive.eai.common.routing.RoutingManager;
import com.eactive.eai.common.routing.RoutingVO;
import com.eactive.eai.common.util.Logger;

public class WarmupManager implements Lifecycle {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private static WarmupManager instance;
	private LifecycleSupport lifecycle = new LifecycleSupport(this);

	private boolean started;

	private WarmupManager() {
	}

	public static synchronized WarmupManager getInstance() {
		if (instance == null) {
			instance = new WarmupManager();
		}
		return instance;
	}

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

		lifecycle.fireLifecycleEvent(STARTING_EVENT, this);

		RoutingManager manager = RoutingManager.getInstance();
		Iterator<RoutingVO> it = manager.getAllRoutingVOs();

		if (it == null) {
			logger.warn("RoutingManager getAllRoutingVOs  is NULL");
		} else {
			Properties p = new Properties();
			p.put(EAIKeys.CALL_MODE_KEY, EAIKeys.CALL_MODE_WARMUP);
			p.setProperty(RouteKeys.ROUTING_TYPE, RouteKeys.ROUT_CALL);
			while (it.hasNext()) {
				RoutingVO vo = it.next();
				try {
					if (vo == null)
						continue;
					if (vo.getSyncRoutingPath() != null) {
						ElinkESBProcessProxy.callElinkESBProcess(vo.getSyncRoutingPath(), null, true, p);
					}
				} catch (Exception e) {
					logger.warn("WarmupManager] warming up the routing process. - " + vo.getSyncRoutingPath());
				}
			}
		}
		started = true;
		lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
	}

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

		lifecycle.fireLifecycleEvent(STOPING_EVENT, this);

		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;
	}
}
