package com.eactive.eai.httpouttlsinfo;

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.util.Logger;
import com.eactive.eai.data.entity.onl.httpouttlsinfo.HttpOutTlsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

	private HttpOutTlsInfoLoader httpOutTlsInfoLoader;

	private HttpOutTlsInfoMapper httpOutTlsInfoMapper;

	@Autowired
	public HttpOutTlsInfoDAO(HttpOutTlsInfoLoader httpOutTlsInfoLoader,
								   HttpOutTlsInfoMapper httpOutTlsInfoMapper) {

		this.httpOutTlsInfoLoader = httpOutTlsInfoLoader;
		this.httpOutTlsInfoMapper = httpOutTlsInfoMapper;
	}

	public Map<String, HttpOutTlsInfoVO> getAllHttpOutTlsInfos() throws DAOException {

		try {
			Stream<HttpOutTlsInfo> httpOutTlsInfos = httpOutTlsInfoLoader.loadAll();
			Map<String, HttpOutTlsInfoVO> httpOutTlsInfoVOMap = new HashMap<>();

			logger.info("[ @@ Load HttpOutTlsInfo Configuration - starting >>>>>>>>>>>>>>>>> ]");

			httpOutTlsInfos.forEach(httpOutTlsInfo -> {
				HttpOutTlsInfoVO httpOutTlsInfoVO = httpOutTlsInfoMapper.toVo(httpOutTlsInfo);
				logger.info("@ " + httpOutTlsInfoVO.toString());
				httpOutTlsInfoVOMap.put(httpOutTlsInfo.getClientId(), httpOutTlsInfoVO);
			});

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

	public HttpOutTlsInfoVO getHttpOutTlsInfo(String clientId) throws Exception {

		try {
			logger.info("[ @@ Load HttpOutTlsInfo getHttpOutTlsInfo Configuration - starting >>>>>>>>>>>>>>>>> ]");

			HttpOutTlsInfo httpOutTlsInfo = httpOutTlsInfoLoader.findById(clientId)
					.orElseThrow(() -> new DAOException("HttpOutTlsInfo not found for clientId: " + clientId));

			HttpOutTlsInfoVO httpOutTlsInfoVO = httpOutTlsInfoMapper.toVo(httpOutTlsInfo);

			if(logger.isInfo()) {
				logger.info("@ " + httpOutTlsInfoVO.toString());
				logger.info("[>>Load HttpOutTlsInfo getHttpOutTlsInfo Configuration - ended ]");
			}
			return httpOutTlsInfoVO;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICBM205"));
		}
	}

}
