package com.eactive.eai.adapter;

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

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

import com.eactive.eai.adapter.loader.AdapterPropGroupLoader;
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.adapter.AdapterPropGroup;

@Service
@Transactional
public class AdapterPropGroupDAO extends BaseDAO {

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

	@Autowired
	private AdapterPropGroupLoader adapterPropGroupLoader;

	public Map<String, AdapterPropGroupVO> getAllProperties() throws DAOException {

		Map<String, AdapterPropGroupVO> adapterPropGroupVos = new HashMap<>();
		try {
			logger.info("[ @@ Load Adapter Properties Configuration - starting >>>>>>>>>>>>>>>>> ]");

			Iterable<AdapterPropGroup> adapterPropGroups = adapterPropGroupLoader
					.loadAll()
					.collect(Collectors.toList());

			for (AdapterPropGroup adapterPropGroup : adapterPropGroups) {
				AdapterPropGroupVO adapterPropGroupVO = getProperties(adapterPropGroup);
				adapterPropGroupVos.put(adapterPropGroup.getPrptygroupname(), adapterPropGroupVO);
			}

			logger.info("[>>Load Adapter Properties Configuration - ended ]");
			return adapterPropGroupVos;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICPM101"));
		}
	}

	private AdapterPropGroupVO getProperties(AdapterPropGroup adapterPropGroup) {
		AdapterPropGroupVO adapterPropGroupVO = new AdapterPropGroupVO(adapterPropGroup.getPrptygroupname());
		adapterPropGroup.getAdapterProps().forEach(adapterProp -> adapterPropGroupVO
				.addProperty(adapterProp.getId().getPrptyname(), adapterProp.getPrpty2val()));
		return adapterPropGroupVO;
	}

	public AdapterPropGroupVO getProperties(String grpNm) throws DAOException {
		try {
			AdapterPropGroup adapterPropGroup = adapterPropGroupLoader.getById(grpNm);
			return getProperties(adapterPropGroup);
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.make("RECEAICPM103", grpNm));
		}
	}

}