package com.eactive.eai.adapter.socket2;

import com.eactive.eai.adapter.listener.AdapterException;
import com.eactive.eai.adapter.listener.AdapterListenerSupport;
import com.eactive.eai.adapter.socket2.config.SocketAdapterFactory;
import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.common.util.Logger;
 
/**
 * 1. 기능 : Socket Adapter의 기동/중지를 위한 Adapter Listener로 FrameWork에서
 * SocketAdapter를 중지/기동하기 위한 Socket Adapter Listener이다. 2. 처리 개요 : -
 * SocketAdapterManager Instance를 얻은 후 해당 Adapter에 대한 Stop/Start 기능을 수행한다. 3.
 * 주의사항
 * 
 * @param
 * @return
 * @exception
 */
public class SocketAdapterListener extends AdapterListenerSupport {
	static final Logger errLogger = SocketLoggerManager.getInstance().getErrLogger();

	@Override
	public void start() throws AdapterException {
//		SocketAdapterManager manager = SocketAdapterManager.getInstance();
		try {
			if (info == null)
				throw new Exception("SocketAdapterListener | AdapterVO가 NULL입니다.");

			ISocketAdapter adapter =  SocketAdapterFactory.createSocketAdapter(info);
			
			adapter.getContext().setAdapterVO(info);
			if (adapter.getContext().isPermanent()) {
				adapter.setAdapterStatus(false);
			} else {
				adapter.setAdapterStatus(true);
			}
			
			adapter.start();  //.join();
		} catch (Exception e) {
			String errorMessage = info==null? "":info.getName() + " | SocketAdapterListener | cannot start : " + e.getMessage();
			logger.error(errorMessage, e);
			throw new AdapterException(errorMessage);
		}
	}

	@Override
	public void stop() throws AdapterException {

		SocketAdapterManager manager = SocketAdapterManager.getInstance();
		try {
			if (info == null)
				throw new Exception("SocketAdapterListener | AdapterVO가 NULL입니다.");
			
			ISocketAdapter adapter = manager.getSocketAdapter(info.getAdapterGroupName(), info.getName());
			if (adapter == null)
				throw new Exception(info.getName() + " | [SocketAdapterListener] AdapterVO가 NULL입니다.");
			
			adapter.setAdapterStatus(false);

			adapter.stop().join();
		} catch (Exception e) {
			String errorMessage = info==null? "":info.getName() + " | SocketAdapterListener | cannot stop : " + e.getMessage();
			logger.error(errorMessage, e);
			throw new AdapterException(errorMessage);
		}
	}
}
