package com.eactive.eai.transformer.dao.jdbc;

import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Stream;

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

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.transformer.function.Function;
import com.eactive.eai.transformer.dao.FunctionDao;
import com.eactive.eai.transformer.function.FunctionDefinition;
import com.eactive.eai.transformer.function.loader.FunctionLoader;
import com.eactive.eai.transformer.function.mapper.FunctionMapper;

@Service
@Transactional
public class FunctionJdbcDao extends TransDao implements FunctionDao {

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

	@Autowired
	private FunctionLoader functionLoader;

	@Autowired
	private FunctionMapper functionMapper;

	public Map<String, FunctionDefinition> load() {
		if (logger.isInfoEnabled()) {
			logger.info("FunctionJdbcDao | loading... ");
		}

		Map<String, FunctionDefinition> map = new TreeMap<>();

		try (Stream<Function> functions = functionLoader.loadAll()) {
			functions.forEach(f -> {
				FunctionDefinition fd = functionMapper.toVo(f);
				map.put(fd.getName(), fd);
			});
		}

		if (logger.isDebugEnabled()) {
			logger.debug("FunctionJdbcDao | 함수 정보를 가져왔음 - " + map.size());
		}

		return map;
	}

	public FunctionDefinition findFunctionByName(String cnvsnFuntnname) {
		Optional<Function> functionOptional = functionLoader.findById(cnvsnFuntnname);
		if (!functionOptional.isPresent()) {
			return null;
		}

		Function function = functionOptional.get();
		return functionMapper.toVo(function);
	}

}
