package com.eactive.eai.batch.job.jobItem.zeniel;

import java.io.ByteArrayOutputStream;
import java.util.Properties;

import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;

import com.eactive.eai.batch.common.CommonKeys;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_ZENEL_0600 extends DefaultTelegram implements TelegramService
{
    //>> 업무관리정보
    private final String OpCode_start       = "001";    //업무개시
    private final String OpCode_end         = "002";    //업무종료
    private final String OpCode_exsist      = "003";    //추가송신파일 있음
    private final String OpCode_noexsist    = "004";    //추가송신파일 없음
    private Properties telegramInfo;

    /**
     * 생성자
     */
    public RECV_ZENEL_0600() {
        //업무개시요구 및 업무개시통보
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        return true;
    }

    /**
     * 전문 Validation
     */
    public boolean doValidation()
    {
        if (!super.doValidation()) return false;

        //업무관리정보 유효성 확인
        if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) {
            logger.info("{} BATCH JOB : start request received", logHeader);
            // 거래구분코드(송수신 구분 코드) 체크
            String recvTrGbCd = getFieldValueString(4);
            if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND).equals(recvTrGbCd)){
                logger.info("{} BATCH JOB : send request received", logHeader);
                batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND);
                checkMoreFileinDB();
            }else if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV).equals(recvTrGbCd)){
                logger.info("{} BATCH JOB : recv request received", logHeader);
                setConditionTxt(TelegramKeys.RECV);
                batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE);
            }else{
                logger.info("{} BATCH JOB : send/recv request error", logHeader);
                this.setResolveResponseCode(TelegramKeys.RES_CODE_FORMAT_ERROR);
                setConditionTxt(TelegramKeys.ERROR);
            }

        }
        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) {
            logger.info("{} BATCH JOB : end request received", logHeader);
        }
        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) {
        }
        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) {
        }
        else {
            logger.info("{} 0600 telegram : unknown  Operation code received >> "+this.getOpCode(), logHeader);
            this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED);

            String[] msgArgs = new String[2];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            msgArgs[1] = this.getOpCode();
            String errCode = "BECEAIFJI008";
            String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
        }
        return true;
    }

    public boolean doPreExecute() {
        try {
            if (!super.doPreExecute()) return false;
            telegramInfo = getTelegramInfo();
            return true;
        } catch (Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI003";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            return false;
        }
    }

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
            //DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제)
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=8; i< al_Field.size(); i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
            return true;
        } catch(Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI002";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            return false;
        }
    }
    private void checkMoreFileinDB(){
        String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
        String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
        SchedulerMessageVO info;
        try{
            info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode );
            if ( info == null ) {
                this.setConditionTxt(TelegramKeys.NOFILE);
                return;
            }
            String strUUID = batchDoc.getBatchMsg().getHeader().getUUID();
            String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID();

            //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
            SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID);

            //BatchMsgDoc 값 설정
            batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
            batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
            batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
            batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
            batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
            batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
            batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
            batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
            batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
            batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize());
            batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize());
            batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize());
            batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID());
            batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW());
            batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName());
            this.setConditionTxt(TelegramKeys.SEND);
            LogUtil.updateLogMaster(batchDoc);
        } catch ( Exception e){}
    }

    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
        return super.getFieldValueString(3);
    }
    // 거래구분코드 필드값 리턴
    public String getTrClass()
    {
        return super.getFieldValueString(4);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(7);
    }
    //업무관리코드 필드값 리턴
    public String getOpCode()
    {
        return super.getFieldValueString(9);
    }
}