package com.eactive.eai.adapter;

import java.util.ArrayList;
import java.util.List;
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.AdapterGroupLoader;
import com.eactive.eai.adapter.loader.AdapterLoader;
import com.eactive.eai.adapter.mapper.AdapterGroupMapper;
import com.eactive.eai.adapter.mapper.AdapterMapper;
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.adapter.Adapter;
import com.eactive.eai.data.entity.onl.adapter.AdapterGroup;

@Service
@Transactional
public class AdapterDAO extends BaseDAO {

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

	@Autowired
	private AdapterGroupLoader adapterGroupLoader;

	@Autowired
	private AdapterLoader adapterLoader;

	@Autowired
	private AdapterGroupMapper adapterGroupMapper;

	@Autowired
	private AdapterMapper adapterMapper;

	public List<AdapterGroupVO> getAllAdapterGroups() throws DAOException {
		try {
			List<AdapterGroup> adapterGroups = adapterGroupLoader.selectAllGroups();
			return adapterGroups.stream().map(adapterGroupMapper::toVo).collect(Collectors.toList());
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAAC001"));
		}
	}

	public List<AdapterVO> getAllAdapters(String adapterGroupName) throws DAOException {
		List<AdapterVO> al = new ArrayList<>();

		try {
			Iterable<Adapter> adapters = adapterLoader.selectAdaptersByGroup(
					com.eactive.eai.common.server.Keys.DEFAULT_SERVER, adapterGroupName,
					EAIServerManager.getInstance().getLocalServerName());

			for (Adapter adapter : adapters) {
				AdapterVO vo = adapterMapper.toVo(adapter);
				al.add(vo);
			}
			return al;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAAC002"));
		}
	}

	public AdapterGroupVO getAdapterGroup(String adapterGroupName) throws DAOException {
		try {
			AdapterGroup adapterGroup = adapterGroupLoader.getById(adapterGroupName);
			AdapterGroupVO gvo = adapterGroupMapper.toVo(adapterGroup);
			List<AdapterVO> adapterVos = adapterGroup.getAdapters().stream().map(adapterMapper::toVo)
					.collect(Collectors.toList());

			adapterVos.forEach(gvo::addAdapterVO);
			return gvo;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAAC009"));
		}
	}

}
