package com.eactive.eai.flowcontrol.jms;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import org.apache.commons.lang3.BooleanUtils;
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.server.EAIServerManager;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.flowcontrol.jms.FCQueueReceiver;
import com.eactive.eai.flowcontrol.jms.loader.FCQueueReceiverLoader;
import com.eactive.eai.flowcontrol.jms.mapper.FCQueueReceiverMapper;

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

	@Autowired
	private FCQueueReceiverLoader fcQueueReceiverEntityService;

	@Autowired
	private FCQueueReceiverMapper fcQueueReceiverMapper;

	public Map<String, FCQueueReceiverVO> getAllReceivers() throws DAOException {
		boolean isScalable = BooleanUtils.toBoolean(System.getProperty("scalable"));
		String serverName ="";
		if(isScalable) {
			serverName ="ALL";
		}else {
			serverName = EAIServerManager.getInstance().getLocalServerName();
		}
		try {
			Map<String, FCQueueReceiverVO> fCQueueMap = new HashMap<>();
			Stream<FCQueueReceiver> fcQueuesReceivers = fcQueueReceiverEntityService.loadAll(serverName);
			logger.info("[ @@ Load FCQueueReceiver Configuration - starting >>>>>>>>>>>>>>>>> ]");

			fcQueuesReceivers.forEach(e -> {
				FCQueueReceiverVO fcQueueReceiverVO = fcQueueReceiverMapper.toVo(e);
				fCQueueMap.put(fcQueueReceiverVO.getReceiverName(), fcQueueReceiverVO);
				logger.info("@ " + fcQueueReceiverVO.toString());
			});

			logger.info("[>>Load FCQueueReceiver Configuration - ended ]");
			return fCQueueMap;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICCM101"));
		}
	}

	public FCQueueReceiverVO getReceiver(String queRcverName) throws DAOException {

		try {
			FCQueueReceiver fcQueueReceiver = fcQueueReceiverEntityService.getById(queRcverName);
			FCQueueReceiverVO fcQueueReceiverVO = fcQueueReceiverMapper.toVo(fcQueueReceiver);
			logger.info("@ " + fcQueueReceiverVO.toString());
			return fcQueueReceiverVO;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICCM101"));
		}
	}
}
