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

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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.property.loader.PropGroupLoader;
import com.eactive.eai.data.entity.onl.property.PropGroup;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.transformer.dao.LayoutDao;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.loader.LayoutLoader;
import com.eactive.eai.transformer.layout.mapper.LayoutMapper;
import com.eactive.eai.transformer.util.MemoryLogger;

@Service
@Transactional
public class LayoutJdbcDao extends TransDao implements LayoutDao {

	@Autowired
	private PropGroupLoader propGroupLoader;

	@Autowired
	private LayoutLoader layoutLoader;

	@Autowired
	private LayoutMapper layoutMapper;
	
	@Override
	public Map<String, Layout> load() {
		Stream<LayoutEntity> layoutEntities = layoutLoader.loadAll();
		Map<String, Layout> resultMap = new ConcurrentHashMap<>();

		layoutEntities.forEach(layoutEntity -> {
			Layout layout = load(layoutEntity);
			if (layout != null) {
				resultMap.put(layout.getName(), layout);
			}
		});

		return resultMap;
	}

	public Layout load(LayoutEntity layoutEntity) {
		Layout layout = null;
		try {
			layout = layoutMapper.toVo(layoutEntity);
		} catch (Exception e) {
			MemoryLogger.error(e.getMessage(), e);
			logger.error(e.getMessage(), e);
		}

		return layout;
	}

	public Layout load(String layoutName) {
		LayoutEntity layoutEntity = layoutLoader.getById(layoutName);
		
		if (!"1".equals(layoutEntity.getUseyn())) {
			return null;
		}
		try {
			return load(layoutEntity);
		} catch (Exception e) {
			MemoryLogger.error(e.getMessage(), e);
			logger.error(e.getMessage(), e);
			throw new TransformerDaoException(e.getMessage(), e);
		}
	}


	@Override
	public Layout findLayoutByName(String loutName) {
		LayoutEntity layoutEntity = layoutLoader.getById(loutName);
		return load(layoutEntity);
	}

	@Override
	public Item findItemByName(String layoutName) {
		return load(layoutName).getRootItem();
	}

	@Override
	public Map<String, String> findPermanent() {
		Map<String, String> map = new HashMap<>();
		PropGroup propGroup = propGroupLoader.getById("PERMANENT_LAYOUT");
		propGroup.getProps().forEach(prop -> map.put(prop.getPrpty2val(), prop.getPrpty2val()));
		return map;
	}

}