package com.eactive.eai.common.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eactive.eai.common.logger.EAIDBLogControl;
import com.eactive.eai.common.sessioninfo.SessionInfoDAO;
import com.eactive.eai.common.sessioninfo.SessionInfoVO;
import com.eactive.eai.common.sessioninfo.SessionInfoVO.Status;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;

@Component
public class SessionStatusManager {

	private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

//	private static SessionStatusManager instance;

	@Autowired
	SessionInfoDAO sessionInfoDAO;

	private SessionStatusManager() {
	}

	public static SessionStatusManager getInstance() {
		return ApplicationContextProvider.getContext().getBean(SessionStatusManager.class);
	}

	public void manageStatus(SessionInfoVO sessionInfoVO) {

		if (EAIDBLogControl.isEnable()) {
			try {
				sessionInfoDAO.upsertSessionInfo(sessionInfoVO);
			} catch (Exception e) {
				if (logger.isError()) {
					logger.error("Insert Session DB ERROR. - " + sessionInfoVO.getUserId(), e);
				}
			}
		} else {
			if (logger.isError()) {
				logger.error("EAIDBLogControl is not enable - " + sessionInfoVO.getUserId());
			}
		}

	}

	public void manageLoginStatus(String userId) {
		SessionVO login = SessionManager.getInstance().getLogin(userId);
		Status status = login == null ? SessionInfoVO.Status.inactive : SessionInfoVO.Status.active;
		SessionInfoVO sessionInfoVO = new SessionInfoVO(userId);
		sessionInfoVO.setSessionStatus(status);

		/** upsert **/
		manageStatus(sessionInfoVO);
	}

	public void manageLoginStatusWithUUID(SessionVO session) {

		SessionVO login = SessionManager.getInstance().getHttpLogin(session.getUuid());
		Status status = login == null ? SessionInfoVO.Status.inactive : SessionInfoVO.Status.active;
		String userId = login == null ? session.getLoginUserId() : login.getLoginUserId();
		SessionInfoVO sessionInfoVO = new SessionInfoVO(session.getLoginUserId());
		sessionInfoVO.setSessionId(session.getUuid());
		sessionInfoVO.setUserId(userId);
		sessionInfoVO.setSessionStatus(status);

		/** upsert **/
		manageStatus(sessionInfoVO);
	}
	public void manageWebSocketStatus(String userId, Status status) {
		SessionInfoVO sessionInfoVO = new SessionInfoVO(userId);
		sessionInfoVO.setWsocSessionStatus(status);

		/** upsert **/
		manageStatus(sessionInfoVO);
	}

}
