package com.eactive.eai.batch.scheduler;

import java.util.ArrayList;

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.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.message.EAIBatchMsgManager;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager;
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.dao.Keys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.routing.JMSQueueSender;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.JMSSender;

public class ScheduleHandlerProcess{

	//파일로거
    private static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER);

	public BatchDoc clientRequestwithReturn(
			BatchDoc batchDoc) throws Exception {
		return null;
	}

	public void clientRequest() throws Exception {
		try {
			logger.debug("[스케쥴 핸들러] ■■■■■ 진행중인 일괄전송 작업 건수 : " + BatchRunningJobManager.getInstance().getRunningJobCount() +" ■■■■■");
			logger.info("[스케쥴 핸들러] ============================================================================================");
			logger.info("[스케쥴 핸들러] ■ Job_Queue 테이블에서 진행할 Job을 Job_Processing 테이블로 이동...");

			//Job_Queue 테이블 에서 현재시간에 걸리는 수행 할 작업을 Job_Processing 테이블로 이동
			//망관리에 의하여 해당 망이 사용중인 작업은 걸러짐
			ArrayList<SchedulerMessageVO> executeJobList = SchedulerMessageManager.getInstance().getExecutableJobFromQueue();
			logger.info("[스케쥴 핸들러] ※ 요구송수신 진행 작업 건수: "+ ((executeJobList == null)? 0 : executeJobList.size() ));
			logger.info("[스케쥴 핸들러] ============================================================================================");
			for (SchedulerMessageVO info : executeJobList) {
				try{
					BatchDoc batchDoc = moveJobToProcessing(info);
					String instName = System.getProperty(Keys.SERVER_KEY);
					String jobQueue = instName.equals("bapSvr11") ? Keys.BAP01_JOB_QUEUE : Keys.BAP02_JOB_QUEUE;
					JMSSender.sendToQueue(batchDoc, Keys.CONNECT_FACTORY, jobQueue);
			        //JMSQueueSender sender = new JMSQueueSender();
	//		        logger.debug("[ScheduleHandlerProcess][clientRequest]batchDoc-->" + batchDoc.getBatchMsg().getHeader().getUUID());
			       // sender.sendObject(Keys.CONNECT_FACTORY, Keys.JOB_QUEUE, batchDoc, batchDoc.getBatchMsg().getHeader().getUUID());				
					loggingToDB(batchDoc);
				} catch (Exception e){
					catchException(e);
			}
			}
			
		} catch (Exception e) {
			catchException(e);
		}
		
	}

    private BatchDoc moveJobToProcessing(SchedulerMessageVO info) throws Exception
    {
		//해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
		SchedulerMessageManager.getInstance().moveJobQueueToHandle(info);
		//<------------ 에러시 예외처리 후 다음 작업 수행
		logger.debug("UUID추적:[ScheduleHandlerProcess]:uuid["+info.getUUID() +"]");
		logger.debug("UUID추적:[ScheduleHandlerProcess]:subuuid["+info.getSubUUID() +"]");

		//BatchMsgDoc 생성
		BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsg(true);  //true:초기화함

		//BatchMsgDoc Layer, SubLayer, StartTime 설정
		EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING);

		//BatchMsgDoc 값 설정
		batchMsgDoc.getBatchMsg().getHeader().setUUID(info.getUUID());
		batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode());
		batchMsgDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName());
		batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType());
		batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode());
		batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
		batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
		batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
		batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
		batchMsgDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
		batchMsgDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
		batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName());
		batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
		batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
		batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode());
		batchMsgDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
		batchMsgDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
		batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
//		batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(info.getInstitutionType());
		batchMsgDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize());
		batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize());
		batchMsgDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize());
		batchMsgDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID());
		batchMsgDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW());
		batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(info.getRempoteIP());
		batchMsgDoc.getBatchMsg().getHeader().setPort(info.getRemotePort());
		batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode());
//		batchMsgDoc.getEAIBatchMessage().getHeader().setProtocol("TCP/IP");
//		batchMsgDoc.getBatchMsg().getHeader().setProtocol(info.getProtocol());
		
		// 레코드 크기 추가 2009.02.03
		String jobCode = batchMsgDoc.getBatchMsg().getHeader().getJobCode();
        BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode );
        batchMsgDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize());
        
        // 20120601 추가 -- 시작
        if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) ||
        		info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){
            String hdrInfoName = info.getHdrInfoName();
            batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
            batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
            batchMsgDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));
            batchMsgDoc.getBatchMsg().getHeader().setFileSize(batchMsgDoc.getBatchMsg().getHeader().getRecLen() * batchMsgDoc.getBatchMsg().getHeader().getTotRecCnt());
        }
        // 20120601 추가 -- 여기까지

		RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(info.getFlowRuleCode());
		batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo != null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");

		batchMsgDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID());

		//재처리 플래그 설정..
		if (info.getRecvRetryFlag().equals("1")){
			batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(true);	
			logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 true로 설정합니다." );	
			
		}else {
			batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(false);
			logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 false로 설정합니다." );		
		}
		
		logger.info("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName());
		return batchMsgDoc;
    }
    
    private void loggingToDB(BatchDoc batchMsgDoc) throws Exception
    {
		//요구송수신에 대한 스케쥴핸들러 단계 DB로그 생성
		batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
		LogUtil.setLog(batchMsgDoc);

		//요구송수신 작업 시작정보를 Master 로그에 Update.
		LogUtil.updateLogMaster(batchMsgDoc);
    }

    /* 예외 처리 */
    private void catchException(Exception ex)
    {
		//Exception ex = this.context.getExceptionInfo().getException();
		logger.error("[스케쥴 핸들러] ★★★★★ 예외 발생 !! ★★★★★", ex);
        try {
            // 파일로그 처리
			String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC018");
            logger.error(errMsg, ex);  //Scheduler Handle Processor JPD 에서 에서 오류가 발생하였습니다.

            // DB로그 처리
            //batchMsgDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg);
			//batchMsgDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16());
            //LogUtil.setErrorLog(batchMsgDoc, errMsg);

        } catch (Exception e) {
            logger.error("[스케쥴 핸들러] ★★★★★ 스케쥴 핸들러 예외 처리 중 에러 !! ★★★★★", e);
        }
    }

}
