package com.eactive.eai.common.sessioninfo;

import java.io.IOException;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.sessioninfo.loader.SessionInfoLoader;
import com.eactive.eai.common.sessioninfo.mapper.SessionInfoMapper;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.ObjectUtil;
import com.eactive.eai.data.entity.onl.sessioninfo.SessionInfo;

@Service
@Transactional
public class SessionInfoDAO extends BaseDAO {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	@Autowired
	private SessionInfoLoader sessionInfoLoader;

	@Autowired
	private SessionInfoMapper sessionInfoMapper;
	

	public void upsertSessionInfo(SessionInfoVO vo) throws DAOException {
		SessionInfoVO cloned = null;
		try {
			cloned = (SessionInfoVO) ObjectUtil.deepCopy(vo);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new DAOException(e);
		}
		cloned.setUserId(cloned.getUserId() + "_" + cloned.getSessionId());

		try {
			SessionInfo sessionInfo = null;
			Optional<SessionInfo> optional = sessionInfoLoader.findById(cloned.getUserId());
			if(optional.isPresent()) {
				sessionInfo = optional.get();
		        sessionInfo.setSessionStatus( vo.getSessionStatusInfo() );
		        sessionInfo.setWsocSessionStatus( vo.getWsocSessionStatusInfo() );
//		        sessionInfo.setUserid( vo.getUserId() );
		        sessionInfo.setBrnCd( vo.getBrnCode() );
		        sessionInfo.setBrnName( vo.getBrnName() );
//		        sessionInfo.setCreateTime( vo.getCreateTime() );
		        sessionInfo.setRofcCd( vo.getRofcCode() );
//		        sessionInfo.setSessionId( vo.getSessionId() );
		        sessionInfo.setTerminalId( vo.getTerminalId() );
//		        sessionInfo.setUserName( vo.getUserName() );
		        sessionInfo.setWsocInstance( vo.getWsocInstance() );
		        sessionInfo.setWsocRemoteAddr( vo.getWsocRemoteAddr() );
			}
			else {
				sessionInfo = sessionInfoMapper.toEntity(cloned);
				sessionInfoLoader.save(sessionInfo);
			}
		} catch (Exception e) {
			logger.error(e);
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICKE118"));
		}
	}
	
	public SessionInfoVO getSessionInfo(String userId) throws DAOException {
		try {
			SessionInfo sessionInfo = sessionInfoLoader.getById(userId);
			return sessionInfoMapper.toVo(sessionInfo);
		} catch (Exception e) {
			logger.error(e);
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICKE118"));
		}
	}
}
