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

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.batch.common.StringUtil;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_BOKEX_03100050 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
    public RECV_BOKEX_03100050() {
        //파일 종료 응답
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) 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<9; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=9; i< al_Field.size(); i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
            // 수신 파일 End DB로그
            LogUtil.setLogFileEnd(batchDoc);
            if ( checkMoreFileInDB()){
                this.setConditionTxt("");
            } else {
                this.setConditionTxt(TelegramKeys.NOFILE);
            }

            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 boolean 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 ) {
                return false;
            }
            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());
            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());
            
            String jobCode = batchDoc.getBatchMsg().getHeader().getJobCode();
            BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode );
            batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize());

            String hdrInfoName = info.getHdrInfoName();
            batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
            batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
            batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));
            batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt());

            batchDoc.getBatchMsg().getBody().setCurFileSize(0);
            batchDoc.getBatchMsg().getBody().setSeqNum(0);
            LogUtil.updateLogMaster(batchDoc);
        } catch ( Exception e){
        	logger.warn(e.getMessage(), e);
        	return false;
        }
    	return true;
    }

    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
        String telegramNo = super.getFieldValueString(4);
        if ( telegramNo.length() < 8 ) return "";
        return telegramNo.substring(0,3) + telegramNo.substring(6,7);
    }

    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(8);
    }
}