package com.eactive.eai.inbound.processor;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.common.IoSession;
import com.eactive.eai.common.util.Logger;

public class GWSessionManager {
	private static final Logger logger = Logger.getLogger(Logger.LOGGER_SIFT);

	private static volatile GWSessionManager instance;
	private final ConcurrentHashMap<String, IoSession> sessionMap;
	private final ConcurrentHashMap<String, String> adapterMap;

	private GWSessionManager() {
		this.sessionMap = new ConcurrentHashMap<>();
		this.adapterMap = new ConcurrentHashMap<>();
	}

	public static GWSessionManager getInstance() {
		if (instance == null) {
			synchronized (GWSessionManager.class) {
				if (instance == null) {
					instance = new GWSessionManager();
				}
			}
		}
		return instance;
	}

	public ConcurrentHashMap<String, IoSession> getSessionList() {
		return sessionMap;
	}

	public synchronized void sessionIn(String sessionId, IoSession session) throws Exception {
		logger.info("GWSessionManager ] sessionIn - [{}, {}]", sessionId, (session != null) ? session.toString() : "null");
		if (sessionId != null && session != null) {
			sessionMap.put(sessionId, session);
		}
	}

	public synchronized void sessionOut(String sessionId) {
		logger.info("GWSessionManager ] sessionOut - [{}]", sessionId);
		if (sessionId != null && sessionMap.containsKey(sessionId)) {
			sessionMap.remove(sessionId);
		}
	}

	public synchronized IoSession getSession(String sessionId) {
		if (sessionId != null) {
			IoSession session = sessionMap.get(sessionId);
			logger.info("GWSessionManager ] getSession - [{}, {}]", sessionId, (session != null) ? session.toString() : "null");
			return session;
		}
		return null;
	}

	public ConcurrentHashMap<String, String> getAdapterList() {
		return adapterMap;
	}

	public synchronized void adapterIn(String adapterId, String adapterName) throws Exception {
		logger.info("GWSessionManager ] adapterIn - [{}, {}]", adapterId, adapterName);
		if (adapterId != null && adapterName != null) {
			adapterMap.put(adapterId, adapterName);
		}
	}

	public synchronized void adapterOut(String adapterId) {
		logger.info("GWSessionManager ] adapterOut - [{}]", adapterId);
		if (adapterId != null && adapterMap.containsKey(adapterId)) {
			adapterMap.remove(adapterId);
		}
	}

	public synchronized String getAdapter(String adapterId) {
		if (adapterId != null) {
			String adapterName = adapterMap.get(adapterId);
			logger.info("GWSessionManager ] getAdapter - [{}, {}]", adapterId, adapterName);
			return adapterName;
		}
		return null;
	}
	
	public boolean isExists(String transactionId) {
		if (getSession(transactionId) != null || getAdapter(transactionId) != null) {
			return true;
		}
		return false;
	}
}
