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

import java.util.HashMap;
import java.lang.String;
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_SKT01_2100 extends DefaultTelegram implements TelegramService
{

    /**
     * 생성자
     */
    public RECV_SKT01_2100() {
        //DATA수신
    }

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

            int block_no = batchDoc.getBatchMsg().getBody().getBlockNum();

            //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error
            if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){
                logger.debug("{}  doExecute >> recived block_no is bigger than current block_no", logHeader);
                this.setConditionTxt(TelegramKeys.ERROR);

                String[] msgArgs = new String[3];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                msgArgs[1] = _block_no;
                msgArgs[2] = ""+block_no;
                String errCode = "BECEAIFJI024";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                return false;
            }
            batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no);
            batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
            return true;
        } 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;
        }
    }

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
            JobProcessData job = JobProcessData.getInstance();
            String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
            HashMap<String, Object> hm = job.getBatchStageData(uuid);

            @SuppressWarnings("unchecked")
			HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
            if (block_data == null) {
                block_data = new HashMap<Integer, byte[]>();
            }
            
            String _seq_no = new String ((byte[]) al_Field.get(12));
            int recv_seq_no = Integer.parseInt(_seq_no);

            // 강제 결번 테스트용
//            if ( Math.random() > 0.3 ){
//                block_data.put( new Integer(recv_seq_no-1) ,  (byte[]) al_Field.get(13));
//            }
            block_data.put( new Integer(recv_seq_no-1) ,  (byte[]) al_Field.get(13));
            hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);

			//DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<11; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=11; i< al_Field.size()-1; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            baout.write((byte[])this.al_Field.get(al_Field.size()-1), 0, 12);
            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;
        }
    }

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

    public boolean doPreExecute() {
        try {
            if (!super.doPreExecute()) return false;
            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 String getTelegramType()
    {
		return super.getFieldValueString(3);
    }
    // 거래구분코드 필드값 리턴
//    public String getTrClass()
//    {
//		return super.getFieldValueString(5);
//    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
		return super.getFieldValueString(8);
    }
    //업무관리코드 필드값 리턴
    public String getOpCode()
    {
		return super.getOpCode();
    }

}
