package com.eactive.eai.agent.transaction; 

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.CommonKeys;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.message.EAIBatchMsgManager;
import com.eactive.eai.batch.scheduler.JobFileTransferVO;
import com.eactive.eai.batch.scheduler.JobMasterLogVO;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.UUIDGenerator;

public class ReSendRSDataCommand extends Command{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    public ReSendRSDataCommand(String name) {
        super(name);
    }

    public Object execute() throws CommandException
    {
    	logger.info(this.name +" 이 호출되었습니다.");
    	if ( args == null || !(args instanceof String[]) ) {
            String msg = makeException("BECEAICAG001", null);
            logger.error(msg);
            throw new CommandException(msg);
        }

        try {
			String[] logKeys         = (String[])args;
			String argUUID           = logKeys[0];
			String argSubUUID        = logKeys[1];
			String argSndrcvFileName = logKeys[2];
			
			SchedulerMessageManager manager = SchedulerMessageManager.getInstance();
			JobMasterLogVO          vo      = manager.getJobLogByKey(argUUID, argSubUUID);
			JobFileTransferVO       fvo     = manager.getFileLogList(argUUID, argSubUUID, argSndrcvFileName);
			
			if (fvo == null ){
				logger.warn("fail.. 전송할 파일명이 설정되어 있지 않습니다.  파일명이 설정된 단계까지 실행되었는지 확인 필요합니다.");
				return "fail.. 전송할 파일명이 설정되어 있지 않습니다.  파일명이 설정된 단계까지 실행되었는지 확인 필요합니다.";
			}else {
		    	SchedulerMessageVO scheduleInfo = SchedulerMessageManager.getInstance().getScheduleInfo(fvo.getBjobTranDstcdName(), vo.getProcessCode(), vo.getOrganCode());
		    	String strEndTime   = scheduleInfo.getEndTime();
				String strStartTime = CalendarUtil.getCurrentTimeNoDash().substring(8,12);
				
				int endTime = Integer.parseInt(strEndTime);
				int startTime = Integer.parseInt(strStartTime);
				
				if (startTime > endTime){
					strEndTime = "2359";		//하루의 마지막 시간으로 설정
				}

				String newUuid = UUIDGenerator.getUUID();
	
	    		scheduleInfo.setUUID           (argUUID);//로깅을 위해 새로운 uuid 할당한다.
	    		scheduleInfo.setSubUUID        (newUuid);
	    		scheduleInfo.setFilePath       (fvo.getFilePath());
	    		scheduleInfo.setFileName       (fvo.getFileName());
	    		scheduleInfo.setRenamedFileName(fvo.getRenamedFileName());
	    		scheduleInfo.setHdrInfoName    (fvo.getHdrInfoName());

	    		scheduleInfo.setStartTime(DatetimeUtil.getCurrentDate() + strStartTime + "00" + "000" ); 
	    		scheduleInfo.setEndTime  (DatetimeUtil.getCurrentDate() + strEndTime   + "00" + "000" ); 
		
				BatchDoc newBatchDoc =  EAIBatchMsgManager.createBatchMsg(true);         	
				newBatchDoc.getBatchMsg().getHeader().setBatchStartTime(CalendarUtil.getCurrentTimeNoDash());
				newBatchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
	    		
				//JOB QUEUE 테이블에 등록
	    		int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(scheduleInfo);
	    		logger.info("[요구송신 재전송을 위을 위해  배치 JOB QUEUE 테이블 INSERT 건수: "+ resultCnt);
	
	    		//DB로그를 위해서 조회정보를 batchDoc에 세팅
	    		newBatchDoc.getBatchMsg().getHeader().setUUID(argUUID);
	    		newBatchDoc.getBatchMsg().getBody().setSubUUID(newUuid);
	
	    		newBatchDoc.getBatchMsg().getHeader().setScheduleSTime(scheduleInfo.getStartTime());        //전송 시작 시각
	    		newBatchDoc.getBatchMsg().getHeader().setScheduleETime(scheduleInfo.getEndTime());
	    		newBatchDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_SCHEDULER);
	    		newBatchDoc.getBatchMsg().getHeader().setProcessCode(vo.getProcessCode());
	    		newBatchDoc.getBatchMsg().getHeader().setFileName(fvo.getFileName());
	    		newBatchDoc.getBatchMsg().getHeader().setRenamedFileName(fvo.getRenamedFileName());
	    		newBatchDoc.getBatchMsg().getHeader().setHdrInfoName(fvo.getHdrInfoName());
	    		newBatchDoc.getBatchMsg().getHeader().setScheduleCode(vo.getScheduleCode());
	    		newBatchDoc.getBatchMsg().getHeader().setProcessType(vo.getProcessType());
	    		newBatchDoc.getBatchMsg().getHeader().setInstitutionCode(vo.getOrganCode());
	    		newBatchDoc.getBatchMsg().getHeader().setUserID(vo.getMsgSenderId());
	    		newBatchDoc.getBatchMsg().getHeader().setUserName(vo.getMsgSenderName());
	    		newBatchDoc.getBatchMsg().getHeader().setSystemConnCode(vo.getSystemConnCode());
	    		newBatchDoc.getBatchMsg().getHeader().setRemoteIP(vo.getRemoteServerIp());
	    		newBatchDoc.getBatchMsg().getHeader().setRuleCode(vo.getRuleCode());

	    		
	    		newBatchDoc.getBatchMsg().getBody().setWLIServerName(vo.getWeblogicName());
	    		newBatchDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_QUEUE);
	    		newBatchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
	    		newBatchDoc.getBatchMsg().getBody().setErrorCode(0);
	    		newBatchDoc.getBatchMsg().getBody().setErrorMsg("");
	    		newBatchDoc.getBatchMsg().getBody().setRetryCount(scheduleInfo.getRecvFailCnt());
	
	    		//요구송신 재처리에  대한 최초 DB로그. StartLog 호출.
	    		LogUtil.setStartLog (newBatchDoc);
			}

			return "재전송을 위한 작업큐에 데이터가 추가되었습니다.";
        } catch (Exception ex) {
            String msg = makeException("BECEAICAG002", ex);
            logger.error(msg, ex);
            throw new CommandException(msg);
        }
    }

}
