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

import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;

import com.eactive.eai.common.exception.ExceptionUtil;

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


public class RECV_BI0420 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
	private int recv_seq_no=0;
	
    public RECV_BI0420() {
        // 결번확인지시
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        
        String _seq_no = new String ((byte[]) al_Field.get(8));
        recv_seq_no = Integer.parseInt(_seq_no);

        int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum();

        if (recv_seq_no < seq_no){
            // 0410으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함.
            this.setConditionTxt(TelegramKeys.ERROR);
            logger.debug("{"+logHeader+"}  current block_no is bigger than received block_no");

            String[] msgArgs = new String[3];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            msgArgs[1] = _seq_no;
            msgArgs[2] = ""+seq_no;
            String errCode = "BECEAIFJI024";
            String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);

            return false;
        }
        
        if (recv_seq_no > seq_no){
        	batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
        	
        	JobProcessData job = JobProcessData.getInstance();
            String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
            HashMap<String, Object> hm = job.getBatchStageData(uuid);

//            HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA);	//결번이후에 수신된 데이터 보관..
//            if (block_data == null) {
//                block_data = new HashMap();
//            }
            
            
            @SuppressWarnings("unchecked")
			HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA);		//결번여부 저장..
            if (miss_data == null) {
            	miss_data = new HashMap<Integer, String>();
            }
            
            @SuppressWarnings("unchecked")
			HashMap<String, Integer> first_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_FIRST_MISS);		//첫번째 결번
            @SuppressWarnings("unchecked")
			HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_LAST_MISS);		//마지막  결번 위치 저장

            int missCount = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
            
            if (first_miss_field == null){              	
            	first_miss_field = new HashMap<String, Integer>();
            	first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(seq_no+1));
            	hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field);
            		
            	for (int i=seq_no; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅              		
            		miss_data.put(new Integer(i), "0");
            		hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
            		
            		last_miss_field = new HashMap<String, Integer>();
	            	last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i));
	            	hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
            		
            		missCount = missCount+1;
            	}
            	
            	this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);

            } else { //이전에 miss_field가 있으면             	
            	for (int i=seq_no; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅           		
            		miss_data.put(new Integer(i), "0");
            		hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
            		
            		last_miss_field = new HashMap<String, Integer>();
	            	last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i));
	            	hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
            		
            		missCount = missCount+1;
            	}
            			            	
            	this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);
            }
        }
        
        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<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
                byte[] barr = (byte[])this.al_Field.get(i);
                if ( barr[0] != '\0') {
                    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 );
            setConditionTxt(TelegramKeys.ERROR);
            return false;
        }
    }

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