package com.eactive.eai.adapter.http.client;

import java.util.Properties;

import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.http.dynamic.HttpLoggerManager;
import com.eactive.eai.adapter.listener.AdapterException;
import com.eactive.eai.adapter.listener.AdapterListenerSupport;
import com.eactive.eai.common.util.Logger;

public class HttpClientAdapterListener extends AdapterListenerSupport {
	final static Logger logger2 = HttpLoggerManager.getInstance().getLogger();
	final static Logger errLogger = HttpLoggerManager.getInstance().getErrLogger();

	public void start() throws AdapterException {
		
		try {
			if (info == null) {
				throw new Exception("HttpClientAdapterListener | AdapterVO가 NULL입니다.");
			}
			AdapterPropManager manager = AdapterPropManager.getInstance();
			Properties outboundProp = manager.getProperties(info.getPropGroupName());
			String adapterGroupName = info.getAdapterGroupName();
			String adapterName = info.getName();
			String httpType = outboundProp.getProperty(HttpClientAdapterServiceKey.HTTP_TYPE); 
			HttpClientAdapterServiceFactory.createFactory(httpType, adapterGroupName, adapterName);
			if(logger2.isInfo()) {
				logger2.info("[HttpClientAdapterListener] AdapterName [" + info.getAdapterGroupName() + "." + info.getName()
						+ "] httpType [" + httpType + "] start");
			}
			info.setStatus(true);
		} catch (Exception e) {
			logger.error(info.getName() + " | HttpClientAdapterListener | cannot start : " + e.getMessage(), e);
			throw new AdapterException(info.getName() + " | HttpClientAdapterListener | cannot start - " + e.getMessage());
		}
	}

	public void stop() throws AdapterException {
		try {
			if (info == null) {
				throw new Exception("HttpClientAdapterListener | AdapterVO가 NULL입니다.");
			}
			String adapterName = info.getName();
			HttpClientAdapterServiceFactory.removeFactory(adapterName);
			if(logger2.isInfo()) {
				logger2.info("[HttpClientAdapterListener] AdapterName [" + info.getAdapterGroupName() + "." + info.getName()
						+ "] adapter info [" + info + "] stop");
			}
			info.setStatus(false);
		} catch (Exception e) {
			logger.error(info.getName() + " | HttpClientAdapterListener | cannot stop : " + e.getMessage(), e);
			throw new AdapterException(info.getName() + " | HttpClientAdapterListener | cannot stop - " + e.getMessage());
		}
	}
}
