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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Properties;

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;

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

public class SEND_BOKEX_03100040 extends DefaultTelegram implements TelegramService
{
    private int SEND_LENGTH;            //길이 필드를 제외한 전문의 총길이
    private int REAL_SEND_LENGTH;       //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)

    private Properties       telegramInfo;
    private File             file;
    private FileOutputStream fout;
    private String           RTN_CD;

    /**
     * 생성자
     */
    public SEND_BOKEX_03100040() {
        //결번확인통보
    }

    /**
     * 전문조립
     */
    public boolean doExecute() {
        try {

            boolean result = compareSeqNSize();
            if (!result) return false;

            result = calculateSendLength();
            if (!result) return false;

            int i = -1;
            //전문송신  전체 Byte 수
            compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);

            // Transaction Code
            compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);

            //업무구분코드 - FXB
            compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);

            // 참가기관코드
            compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);

            //전문종별코드.
            compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);

            //송수신 FLAG : 전문 발생 기관을 구분하여  아래의 값을 SET한다.
            compileField(++i, getFldTrClass(), this.al_FieldProps[i]);

            //기관구분
            compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);

            //계속여부
            compileField(++i, "N", this.al_FieldProps[i]);

            //응답코드
            compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
            // 여기 까지 공통부

            //결과
            compileField(++i, RTN_CD, this.al_FieldProps[i]);

            //시퀀스
            compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]);

            //수신크기
            compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]);
            //<< 전문 완성
            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() {
        try {
            if (!super.doPostExecute()) return false;

            if ( fout != null ){
                fout.close();
            }
            //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()));

            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 boolean doPreExecute() {
        try {
            if (!super.doPreExecute()) return false;
            telegramInfo = getTelegramInfo();
            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 int getSendLength()
    {
        try {
            return REAL_SEND_LENGTH;  //실 DATA BYTE수
        } catch (Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI013";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);

            logger.error( e.getMessage(), e);
            return -1;
        }
    }

    private boolean calculateSendLength () {
        try {
            for (int i=1; i< this.al_Field.size(); i++) {
                byte[] aField = (byte[]) this.al_Field.get(i);
                SEND_LENGTH += aField.length;
            }
            REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
        } catch (Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI025";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( e.getMessage(), e);
            return false;
        }

        return true;
    }

    private boolean compareSeqNSize() {
        try {

            String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
            int  seq_no   = this.batchDoc.getBatchMsg().getBody().getSeqNum();
            long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize();

            // 이전 전문에서 저장한 전문 내용을 꺼내어 본다. 17 자리라고 가정
            String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody());
            int  recv_seq_no   = Integer.parseInt(recvTelegramBody.substring(0, 7));
            long recv_cur_size = Integer.parseInt(recvTelegramBody.substring(7,17));

            if ( cur_size == recv_cur_size){
                if ( seq_no == recv_seq_no ){
                    RTN_CD = "00";
                } else {
                    RTN_CD = "01";
                }
            } else {
                if ( seq_no == recv_seq_no ){
                    RTN_CD = "10";
                } else {
                    RTN_CD = "11";
                }
            }

            HashMap<String, Object> hm = JobProcessData.getInstance().getBatchStageData(uuid);
            @SuppressWarnings("unchecked")
            HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>)hm.get(JobProcessData.PROCDATA_BLOCKDATA);

            if (block_data == null ){
                logger.debug("{"+logHeader+"}"+" {"+ExceptionUtil.getErrorCode("RECIVED FILE DATA IS NULL")+"}");
                String[] msgArgs = new String[1];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                String errCode = "BECEAIFJI026";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                return false;
            }

            if (RTN_CD.equals("00")) {
                if (!createFile()) {
                    return false;
                }
                for (int i = 0; i<seq_no; i++) {        //받은 seq_no만큼만 데이터 확인하여 기록
                    byte[] data = (byte[]) block_data.get(new Integer(i));
                    if (data != null ) fout.write(data);
                }
            }

            hm.put(JobProcessData.PROCDATA_BLOCKDATA, null);    //데이터 기록 여부와 관계 없이  Vector 초기화

        } catch (Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI027";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( e.getMessage(), e);
            return false;
        }
        return true;
    }

    private boolean createFile (){
        try {
            String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath();
            if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) {
                strFullPath = strFullPath + File.separator;
            }
            strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName();
            logger.info("{}  getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader);
            file = new File(strFullPath);
            fout = new FileOutputStream(file, true);
        } catch (Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI028";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( 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);
    }
}