package com.eactive.eai.agent.transaction; 

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

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.running.BatchRunningJobManager;
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;
import com.jcraft.jsch.ChannelSftp;

public class JobUserCancelCommand extends Command{

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

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

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

        try {
			Map<String, Object>paramMap = (HashMap)args;
			
			String bjobDmndMsgID = (String)paramMap.get("bjobDmndMsgID");
			
			BatchDoc batchDoc = BatchRunningJobManager.getInstance().getRunningDocument(bjobDmndMsgID);
			
			if (batchDoc == null){
				return bjobDmndMsgID+"에 해당하는 Batch Job이 없습니다.";
			}
			
			batchDoc.setUserCancel(true);
			ChannelSftp channelSftp = batchDoc.getSftpChannel();
			Object ioStream = batchDoc.getIOStream();
			if (channelSftp == null && ioStream == null){
				return "실행중인 sFTP 송수신이 없습니다.";
			}
			
			if(channelSftp != null)channelSftp.quit();
			if(ioStream != null){
				if(ioStream instanceof InputStream)((InputStream)ioStream).close();
				else if(ioStream instanceof OutputStream)((OutputStream)ioStream).close();
			}
			
        } catch (Exception ex) {
            String msg = makeException("RECEAIMCM002", ex);
            logger.error(msg, ex);
            throw new CommandException(msg);
        }
        
		return "전송종료를 요청했습니다.";
    }

}
