package com.eactive.eai.adapter;

import java.util.concurrent.ConcurrentHashMap;

import com.eactive.eai.adapter.amq.AMQSenderAdapter;
import com.eactive.eai.adapter.app.BusinessApplicationAdapter;
import com.eactive.eai.adapter.http.client.HttpClientAdapterMain;
import com.eactive.eai.adapter.jtc.JtcClientAdapter;
import com.eactive.eai.adapter.socket2.SocketAdapterFacade;
import com.eactive.eai.adapter.wca.SNAAdapterClient;
import com.eactive.eai.adapter.websocket.WebSocketAdapterFacade;
import com.eactive.eai.adapter.webt.WebTClientAdapter;
import com.eactive.eai.common.util.Logger;

public class ElinkAdapterFactory {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static final ElinkAdapterFactory factory = new ElinkAdapterFactory();
	private ConcurrentHashMap<String, ElinkAdapter> adapterMap;

	private ElinkAdapterFactory() {
		adapterMap = new ConcurrentHashMap<>();
	}

	public static ElinkAdapterFactory newInstance() {
		return factory;
	}

	public ElinkAdapter getElinkAdapter(String adapterTypeName) throws Exception {
		ElinkAdapter adapter = adapterMap.get(adapterTypeName);
		if (adapter == null) {
			adapter = createAdapter(adapterTypeName);
		}
		if (adapter == null) {
			throw new RuntimeException("등록된 어댑터 타입을 찾을 수 없습니다. - " + adapterTypeName);
		}
		return adapter;
	}

	private ElinkAdapter createAdapter(String adapterTypeName) throws Exception {
		if (adapterTypeName == null) {
			return null;
		}

		ElinkAdapter adapter = null;

		if (adapterTypeName.equals(Keys.TYPE_HTTP)) {
			adapter = new HttpClientAdapterMain();
			adapterMap.put(Keys.TYPE_HTTP, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_NET2)) {
			adapter = SocketAdapterFacade.getInstance();
			adapterMap.put(Keys.TYPE_NET2, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_WSK)) {
			adapter = WebSocketAdapterFacade.getInstance();
			adapterMap.put(Keys.TYPE_WSK, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_WBT)) {
			adapter = new WebTClientAdapter();
			adapterMap.put(Keys.TYPE_WBT, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_JTC)) {
			adapter = new JtcClientAdapter();
			adapterMap.put(Keys.TYPE_JTC, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_APP)) {
			adapter = new BusinessApplicationAdapter();
			adapterMap.put(Keys.TYPE_APP, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_SNA)) {
			adapter = new SNAAdapterClient();
			adapterMap.put(Keys.TYPE_SNA, adapter);
		} else if (adapterTypeName.equals(Keys.TYPE_AMQ)) {
			adapter = new AMQSenderAdapter();
			adapterMap.put(Keys.TYPE_SNA, adapter);
		} else {
			logger.warn("Unknown adapter type : " + adapterTypeName);
		}
		return adapter;
	}
}
