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

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

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

import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_SSNBT_0310 extends DefaultTelegram implements TelegramService
{

    private int INFORMALFIELD_INDEX = 6;
    private ByteArrayOutputStream bout;

    /**
     * 생성자
     */
    public RECV_SSNBT_0310() {
        //DATA송신
        bout = new ByteArrayOutputStream();
    }

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

    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(7));
            int recv_seq_no = Integer.parseInt(_seq_no);

            batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);

            int dataSize = Integer.parseInt(new String ((byte[]) al_Field.get(5)));
            byte[] recvData = new byte[dataSize];
            System.arraycopy(bout.toByteArray(), 0, recvData, 0, dataSize);

            block_data.put( new Integer(recv_seq_no - 1), recvData);
            hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);

            if ( recv_seq_no == 1 ){ // 첫 레코드이면
                String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
                String bizCode     = batchDoc.getBatchMsg().getHeader().getBizCode();
                BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
                String pattern = null;
                if ( bJobInfo!= null ){
                    pattern = bJobInfo.getSndrcvFileName();
                }
                String recvFileName = FileUtil.getRecvFileName(bizCode, pattern, batchDoc);
                batchDoc.getBatchMsg().getHeader().setFileName(recvFileName);
            	batchDoc.getBatchMsg().setFileHeader(new String(recvData));
            	LogUtil.setLogFileStart(batchDoc);
            }

            //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++) {
            	if ( i != 6 ){
                	baout.write((byte[])this.al_Field.get(i));
            	}else{
                	baout.write(bout.toByteArray());
            	}
            }
            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;
    }

    /**
     * int getCalculatedLength(int idx)
     * --------------------------------------------------------------------------------------
     * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
     * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
     * SEND : 송신 길이 계산
     * RECV : 수신 길이 계산
     */
    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 < this.al_Field.size(); inx++) {
                    if ( inx != idx ){
                    	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 boolean doInformalField(int idx, byte[] data, int length)
    {
        try {
            if (idx == INFORMALFIELD_INDEX) {
                bout.write(data, 0, length);
            } else {
                logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader);
                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 false;
            }
        } catch (Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI004";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            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(2);
    }

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