package com.eactive.eai.message.layout;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.common.stdmessage.loader.StandardMessageLayoutDeployLoader;
import com.eactive.eai.common.stdmessage.loader.StandardMessageLayoutLoader;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.stdmessage.StandardMessageLayoutDeploy;
import com.eactive.eai.data.entity.onl.stdmessage.StandardMessageLayoutItem;
import com.eactive.eai.message.StandardItem;

@Component
@Transactional
public class DatabaseReader implements LayoutReader {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	
	@Autowired
	private StandardMessageLayoutDeployLoader standardMessageLayoutDeployLoader;
	
	@Autowired
	private StandardMessageLayoutLoader standardMessageLayoutLoader;

	@Override
	public ArrayList<StandardItem> parse(String layoutName) throws Exception {
		logger.info("DB Reader Init");
		
		boolean isMaster = false;
		String targetLayoutName = null;
		if(StringUtils.isBlank(layoutName)){
			StandardMessageLayoutDeploy deploy = standardMessageLayoutDeployLoader.findFirst();
			if(deploy != null){
				targetLayoutName = deploy.getLayoutName();
				isMaster = true;
			}
		}else{
			targetLayoutName = layoutName;
		}

		ArrayList<StandardItem>  list = new ArrayList<>();
		if(StringUtils.isNotBlank(targetLayoutName)){
			//로그 적재 시 사용 될 표준전문 레아이아웃 명을 저장한다(현재 로그저장 아키텍처 개선방안이 없어 임시로 작성한 코드이다)
			// SUB 표준전문 로딩으로 로직 수정함.
			if(isMaster) {
				System.setProperty("STANDARD_LAYOUT_NAME", targetLayoutName);
				logger.info("DB Reader Target Layout Name - {}", targetLayoutName);
			}
			Collection<StandardMessageLayoutItem> entityList = standardMessageLayoutLoader.getById(targetLayoutName)
					.getStandardMessageLayoutItems();

			for (StandardMessageLayoutItem entityItem : entityList) {
				StandardItem item = new StandardItem(entityItem);
				list.add(item);
			}
		}

		return list;
	}
}
