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

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_DEBIT_0330 extends DefaultTelegram implements TelegramService {

    /**
     * 생성자
     */
    public RECV_DEBIT_0330() {
        //HEADER/TRAILER 수신
    }

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

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=7; i< al_Field.size(); i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
            
            if( super.getFieldValueString(8).equals( "0000") ) {
                LogUtil.setLogFileStart(batchDoc);
                batchDoc.getBatchMsg().getBody().setBlockNum(0);
                batchDoc.getBatchMsg().getBody().setSeqNum(0);
                if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){
                    this.setConditionTxt(TelegramKeys.NOBODY);
                }

            } else if (super.getFieldValueString(8).equals( "9999")) {
                LogUtil.setLogFileEnd(batchDoc);
            }

            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;
        }
    }
    public int getCalculatedLength(int idx) {
        if (idx >= this.getFieldCount()) {
            logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);

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

            return -1;
        }
        if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
            try {
                String byte_size = new String ((byte[]) al_Field.get(0));
                logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader);
                int preLen = 0;
                for (int inx = 1; inx < idx; inx++) {
                    byte[] aField = (byte[]) this.al_Field.get(inx);
                    preLen += aField.length;
                }
                return Integer.parseInt(byte_size) - preLen;
            } catch(Exception e) {
                String[] msgArgs = new String[1];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                String errCode = "BECEAIFJI005";
                String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                logger.error( e.getMessage(), e);
                return -1;
            }

        } else {

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

            return -1;
        }
    }

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