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

import java.util.Map;
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.data.entity.onl.transformer.transform.TransformEntity;
import com.eactive.eai.transformer.dao.TransformDao;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.loader.TransformLoader;
import com.eactive.eai.transformer.transform.mapper.TransformEntityMapper;
import com.eactive.eai.transformer.util.MemoryLogger;

@Service
@Transactional
public class TransformJdbcDao extends TransDao implements TransformDao {

	@Autowired
	private TransformLoader transformLoader;

	@Autowired
	private TransformEntityMapper transformEntityMapper;

	@Autowired
	private LayoutManager layoutManager;

	public Map<String, Transform> load() {
		if (logger.isInfoEnabled()) {
			logger.info("TransformJdbcDao | loading... ");
		}
		Stream<TransformEntity> transformEntities = transformLoader.loadAll();
		if (logger.isInfoEnabled()) {
			logger.info("TransformJdbcDao | make transform... ");
		}

		return load(transformEntities);
	}
	
	private Map<String, Transform> load(Stream<TransformEntity> transformEntities) {
		Map<String, Transform> map = new TreeMap<>();
		transformEntities.map(this::load).filter(e -> e != null).forEach(t -> map.put(t.getName(), t));
		return map;
	}

	public Transform load(TransformEntity transformEntity) {
		Transform transform = null;
		try {
			transform = transformEntityMapper.toVo(transformEntity);
		} catch (Exception e) {
			MemoryLogger.error("TransformJdbcDao | transform rule load error - " + e.getMessage(), e);
			logger.error("TransformJdbcDao | transform rule load error - " + e.getMessage(), e);
		}
		return transform;
	}

	public Transform findTransformByName(String transformName) {
		TransformEntity transformEntity = transformLoader.getById(transformName);

		Stream<String> layoutNames = transformEntity.getTransformTypeEntities().stream()
				.map(transformTypeEntity -> transformTypeEntity.getId().getLoutname());
		layoutNames.forEach(layoutManager::reload);

		return transformEntityMapper.toVo(transformEntity);
	}

}
