package com.eactive.eai.common.submessage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.submessage.loader.SubMessageInfoLoader;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.submessage.SubMessageInfo;
import com.eactive.eai.data.entity.onl.submessage.SubMessageItem;

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

	@Autowired
	private SubMessageInfoLoader subMessageInfoLoader;

	public Map<String, HashMap<String, String>> getAllSubMessages() throws DAOException {
		HashMap<String, HashMap<String, String>> all = new HashMap<>();
		try {
			List<SubMessageInfo> list = subMessageInfoLoader.selectAll();
			for (SubMessageInfo info : list) {
				String key =info.getBzwksvckeyname();
				List<SubMessageItem> items = info.getSubMessageItems();
				HashMap<String, String> map = new HashMap<>();
				for (SubMessageItem item : items) {
					map.put(item.getId().getColumnname(), item.getColumnvalue());
				}
				all.put(key, map);
			}
			return all;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICKE102"), e);
		}
	}

	public Map<String, String> getSubMessage(String serviceKey) throws DAOException {
		try {
			Optional<SubMessageInfo> optional = subMessageInfoLoader.findById(serviceKey);
			if (optional.isPresent()) {
				SubMessageInfo info = optional.get();
				
				List<SubMessageItem> items = info.getSubMessageItems();
				HashMap<String, String> map = new HashMap<>();
				for (SubMessageItem item : items) {
					map.put(item.getId().getColumnname(), item.getColumnvalue());
				}
				return map;
			} else {
				throw new DAOException("RECEAICKE110");
			}
		} catch (DAOException e) {
			throw e;
		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICKE111"));
		}
	}
}