package com.eactive.eai.rms.ext.tran.epb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.CommonConstants;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;

@Service("tranResultExtractService")
public class TranResultExtractService extends BaseService {
	
	@Autowired
	private TranResultExtractDao tranResultExtractDao;
	
	@Autowired
	private MonitoringContext monitoringContext;
	
	public void tranResultExtract() throws Exception {
		
		/** TargetDatasource Setting **/
		List<DataSourceType> datasourceList = new ArrayList<>();
		datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.EAI));
		datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.FEP));
		
		/** YesterDay & TableName **/
		String yesterday = CommonUtil.getDiffHourDate(DatetimeUtil.getCurrentDate(), -24, "");
		String tranDay = yesterday.substring(0, 8);
		String tableName = "TSEAILG1" + DatetimeUtil.getDayOfWeekNum(DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", yesterday));
		
		for(DataSourceType datasource : datasourceList) {
			
			DataSourceContextHolder.setDataSourceType(datasource);
			logger.debug("Job datasource name : " + datasource.getName());
			
			HashMap paramMap = new HashMap<>();
			paramMap.put("serviceType", datasource.getName());
			paramMap.put("tableName", tableName);
			paramMap.put("tranDay", tranDay);
			
			List<String> tranResultList = tranResultExtractDao.selectTranResultList(paramMap);
			logger.debug("Query result : " + tranResultList.toString());
			
			if(tranResultList.size() == 0) { continue; }
			
			String directory = monitoringContext.getStringProperty(MonitoringContext.FILE_PATH_KEY);
			/** TODO serverType **/
			String serverType = CommonConstants.SERVER_TYPE.equals(CommonConstants.DB_MANAGE_TYPE_S)? CommonConstants.DB_MANAGE_TYPE_T : CommonConstants.SERVER_TYPE;
			/** TODO serverType **/
			String sendFileName = "IF_TRAN_" + serverType + "_" + datasource.getName() + "_" + tranDay + ".dat";
			String sendFileContent = makeSendFileContent(tranResultList);
			String checkFileName = sendFileName + ".chk";
			String checkFileContent = makeCheckFileContent(sendFileName);
			
			/** validation **/
			if(!directory.endsWith("/")) { directory += "/"; }
			boolean matches = sendFileName.matches("IF_TRAN_(T|D|P)_(EAI|FEP)_([0-9]{8}).dat");
			if(!matches) {
				throw new Exception("File Name invaild : " + sendFileName);
			}
			
			logger.debug("File directory : " + directory);
			logger.debug("Send File name : " + sendFileName);
			logger.debug("Send File content : " + sendFileContent);
			logger.debug("Check File name : " + checkFileName);
			logger.debug("Check File content : " + checkFileContent);
			
			FileWriteUtil.FileWrite(directory, sendFileName, sendFileContent);
			FileWriteUtil.FileWrite(directory, checkFileName, checkFileContent);
			
		}
	}

	private String makeSendFileContent(List<String> tranResultList) {
		StringBuilder sb = new StringBuilder();
		for(String tranResult : tranResultList) {
			sb.append(tranResult);
			if(!(tranResultList.indexOf(tranResult) == tranResultList.size() - 1)) {
				sb.append("\n");
			}
		}
		return sb.toString();
	}
	
	private String makeCheckFileContent(String sendFileName) {
		
		String sendInterfaceId = monitoringContext.getStringProperty(MonitoringContext.SEND_IF_KEY);
		String baseDate = ""; // empty 8
		String recNum = ""; // empty 10
		String status = "0";
		
		return new StringBuilder()
				.append(spacing(sendInterfaceId, 30))
				.append(spacing(baseDate, 8))
				.append(spacing(recNum, 10))
				.append(status)
				.append(sendFileName)
				.append("@@").toString();
	}
	
	private String spacing(String str, int length) {
		StringBuilder sb = new StringBuilder();
		sb.append(str);
		for(int i = str.length(); i < length; i++ ) {
			sb.append(" ");
		}
		return sb.toString();
	}
	
}
