package com.eactive.eai.adapter.socket2;

import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.session.SessionManager;
import com.eactive.eai.common.session.SessionVO;
import com.eactive.eai.common.util.Logger;
import org.apache.mina.common.IoSession;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SingleSessionManager {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);	
	  private static SingleSessionManager instance ;
	  
	  private ConcurrentHashMap<String,IoSession> sessionMap ;	  

	  private SingleSessionManager() {
		  this.sessionMap = new ConcurrentHashMap<>();
	  }
	  
	  public static SingleSessionManager getInstance(){
		  if (instance == null){
			  instance = new SingleSessionManager();
		  }
		  return instance;
	  }
	  public ConcurrentMap<String,IoSession> getSessionList(){
		  return sessionMap; 
	  }
	  
	  public synchronized void sessionOpen(String adapterGroupName, IoSession session) throws Exception {
		  logger.warn("SingleSessionManager ] sessionOpen - [" + adapterGroupName +  "," + session + "]");
		  sessionMap.put(adapterGroupName, session);		  
		  EAIServerManager eaiServerManager = EAIServerManager.getInstance();
		  String loginInstId = eaiServerManager.getLocalServerName();
		  
		  SessionVO psessionVo = SessionManager.getInstance().getConnectionInfo(adapterGroupName);
		  if(psessionVo != null) {
			  throw new Exception("Connection already exist in other Server - " + psessionVo.getLoginInstId());
		  }
		  
		  SessionVO sessionVo = new SessionVO();
		  sessionVo.setLoginUserId(adapterGroupName);
		  sessionVo.setLoginInstId(loginInstId);
		  SessionManager.getInstance().putConnectionInfo(adapterGroupName, sessionVo);
	  }
	  
	  public synchronized void sessionClose(String adapterGroupName, IoSession session){
		  try{
			 logger.warn("SingleSessionManager ] closeSession - [" + adapterGroupName +  "," + session + "]");
			 if(adapterGroupName != null) {
				 sessionMap.remove(adapterGroupName);
			 }
			 
			 EAIServerManager eaiServerManager = EAIServerManager.getInstance();
			 String loginInstId = eaiServerManager.getLocalServerName();

			 SessionVO sessionVo = SessionManager.getInstance().getConnectionInfo(adapterGroupName);
			 
			 if(loginInstId != null && sessionVo != null && loginInstId.equals(sessionVo.getLoginInstId())) {
				 SessionManager.getInstance().removeConnectionInfo(adapterGroupName);
			 }
		  }catch(Exception e){
			  logger.error("SingleSessionManager ] Error Occured in Closing session - " + session,e );
		  }
	  }
	  
	  public synchronized IoSession getSession(String adapterGroupName){
		  IoSession session = sessionMap.get(adapterGroupName);
		  logger.warn("SingleSessionManager ] getSession - [" + adapterGroupName +  "," + session + "]");
		  return session;
	  }
}
