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

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

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

    private FileOutputStream fout;
    /**
     * 생성자
     */
    public RECV_FTBAT_0220() {
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        try {
            String _seq_no  = new String ((byte[]) al_Field.get(2));
            int recv_seq_no   = Integer.parseInt(_seq_no);
            int seq_no      = batchDoc.getBatchMsg().getBody().getSeqNum();

            //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error
            if (recv_seq_no != seq_no + 1 ){
                logger.debug("{}  doExecute >> recived seq no isn't match current seq no", logHeader);
                this.setConditionTxt(TelegramKeys.ERROR);

                String[] msgArgs = new String[3];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                msgArgs[1] = _seq_no;
                msgArgs[2] = ""+_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);
            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 {
            if (!createFile()) {
                return false;
            }

            String _size    = new String ((byte[]) al_Field.get(3));
            int recv_size   = Integer.parseInt(_size);
            byte[] data = al_Field.get(4);
            fout.write(data, 0, recv_size);
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + recv_size;
            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
            batchDoc.getBatchMsg().getHeader().setFileSize(lnCurSize);
            
            //DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=1; i<2; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=2; i< al_Field.size()-2; 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;
        }finally{
        	if ( fout != null )
				try {
					fout.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				} 
        		
        }
    }

    /**
     * 전문 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;
        }
    }

    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().getRenamedFileName();
            logger.info("{}  getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader);
            File file = new File(strFullPath);
            fout = new FileOutputStream(file, true);   //bytes will be written to the end of the file rather than the beginning
        } 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()
    {
        return super.getFieldValueString(1);
    }
//    // 거래구분코드 필드값 리턴
//    public String getTrClass()
//    {
//        return super.getFieldValueString(4);
//    }
//    //응답코드 필드값 리턴
//    public String getResCode()
//    {
//        return super.getFieldValueString(7);
//    }
//    //업무관리코드 필드값 리턴
//    public String getOpCode()
//    {
//        return super.getOpCode();
//    }
}