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

import java.io.ByteArrayOutputStream;

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.LogUtil;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_DAC25_130 extends DefaultTelegram implements TelegramService
{

    /**
     * 생성자
     */
    public RECV_DAC25_130() {
        //수신확인
    }

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

            String procYn = new String ((byte[]) al_Field.get(7)); // 처리여부

            if (getResCode().equalsIgnoreCase(TelegramKeys.MAGIC_RES_CODE_SUCESS)
                    && procYn.equalsIgnoreCase("Y")) {
                LogUtil.setLogFileEnd(batchDoc);
                checkMoreFileinDB();
            }else{
                this.setConditionTxt(TelegramKeys.ERROR);
                String[] msgArgs = new String[1];
                msgArgs[0] = getResCode();
                String errCode = "BECEAIFRS021";  //'기타오류'(응답코드:{1}) 응답전문이 수신되었습니다.
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                LogUtil.setLogFileEnd(batchDoc);
            }
        } catch ( Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI001";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( e.getMessage(), e);
            return false;
        }
        return true;
    }

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

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
            //DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<5; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=5; 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(){
        this.setConditionTxt(TelegramKeys.NOFILE);

//        String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
//        String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
//        SchedulerMessageVO info;
//        try{
//            info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode );
//            if ( info == null ) {
//                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().setBizCode(info.getBizCode());
//            BatchJobInfoVO bjInfo = DirInfoManager.getInstance().getFileInfo(info.getJobCode());
//            batchDoc.getBatchMsg().getHeader().setRecLen((int)bjInfo.getFileRecSize());
//            batchDoc.getBatchMsg().getHeader().setFileSize(0);
//            batchDoc.getBatchMsg().getBody().setCurFileSize(0);
//            this.setConditionTxt("");
//
//        } catch ( Exception e){
//
//        }
    }
    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
        return super.getFieldValueString(1);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(2);
    }

}
