package com.eactive.eai.adapter.websocket;

import java.util.Properties;

import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.listener.AdapterException;
import com.eactive.eai.adapter.listener.AdapterListenerSupport;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class WebSocketAdapterListener extends AdapterListenerSupport {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public void start() throws AdapterException {
		WebSocketAdapterManager manager = WebSocketAdapterManager.getInstance();

		AdapterPropManager pmanager = AdapterPropManager.getInstance();
		Properties prop = pmanager.getProperties(info.getPropGroupName());

		try {
			if (info == null)
				throw new Exception("WebSocketAdapterListener | AdapterVO is NULL.");
			WebSocketHandler adapter = new WebSocketHandler(info, prop);
			info.setStatus(true);
			adapter.start();
			manager.addAdapter(info, adapter);
		} catch (Exception e) {
			logger.error("WebSocketAdapterListener] start failed - " + (info == null ? info : info.getPropGroupName()),
					e);
			;
			String errCode = ExceptionUtil.getErrorCode(e, "RECEAIOIA008");
			throw new AdapterException(errCode);
		}
	}

	public void stop() throws AdapterException {
		WebSocketAdapterManager manager = WebSocketAdapterManager.getInstance();
		try {
			WebSocketHandler adapter = manager.getAdapter(info);
			if (adapter == null)
				throw new Exception(info.getName() + " | [WebSocketAdapterListener] AdapterVO is NULL.");
			if (logger.isWarn())
				logger.warn("WebSocketAdapterListener] stop - " + (info == null ? info : info.getPropGroupName()));
			;
			adapter.stop(10 * 1000);
		} catch (Exception e) {
			logger.error("WebSocketAdapterListener] stop failed - " + (info == null ? info : info.getPropGroupName()),
					e);
			;
			String errCode = ExceptionUtil.getErrorCode(e, "RECEAIOIA009");
			throw new AdapterException(errCode);
		}

	}
}
