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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

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.common.exception.ExceptionUtil;

public class RECV_SCBANK_SND extends DefaultTelegram implements TelegramService
{

    private ByteArrayOutputStream bout;
    private int REAL_BYTE;

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

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        try {
            String isEOF       = new String ((byte[]) al_Field.get(2));
            String bizFld      = new String ((byte[]) al_Field.get(3));
            int recv_seq_no    = Integer.parseInt(bizFld.substring(0, 10));

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

            //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error
            if (recv_seq_no !=  seq_no + 1 ){
                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] = "0" + recv_seq_no;
                msgArgs[2] = "0"+ seq_no;
                String errCode = "BECEAIFJI024";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                return false;
            }

            batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
            if ( isEOF.equals(TelegramKeys.MAGICLINK_END )){
            	this.setConditionTxt(TelegramKeys.EOF);
            }
            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 {

			//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로그에 남길 전문 바디 설정
            batchDoc.getBatchMsg().setTelegramBody(new String(bout.toByteArray()));
            
            FileOutputStream fout = createFile();
            if ( fout == null ){
            	return false;
            }
            fout.write(bout.toByteArray());
            fout.close();

            // 전송 상태 처리
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE;
            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);

            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 bizFld      = new String ((byte[]) al_Field.get(3));
                REAL_BYTE = Integer.parseInt(bizFld.substring(10)); 
                return REAL_BYTE;
            } 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 {
        	bout.write(data, 0, length);
        } 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;
        }
    }

    private FileOutputStream createFile () {
    	FileOutputStream fout = null;
    	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 file = new File(strFullPath);
            int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum();
            if ( seq_no > 1 ){
                fout = new FileOutputStream(file, true);
            }else{
                fout = new FileOutputStream(file, false);
            }
        } 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 fout;
    }
    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
		return super.getFieldValueString(1);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
		return super.getFieldValueString(2);
    }

}
