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

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

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.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;

public class SEND_FTBAT_0220 extends DefaultTelegram implements TelegramService
{

    private FileInputStream fin ;
    private int SEQUENCE_NO;
    private int REAL_BYTE;
    private byte[] fileData;

    /**
     * 생성자
     */
    public SEND_FTBAT_0220() {
        //DATA송신
    }

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

            if (!setData()) return false;

            byte[] som = new byte[1];
            byte[] eom = new byte[1];
            som[0] = 0x02;
            eom[0] = 0x03;

            //메시지 시작 문자
            al_Field.set(0, som);

            //메시지 타입
            compileField(1, this.getFldTelegramType(), this.al_FieldProps[1]);

            compileField(2, ""+SEQUENCE_NO, this.al_FieldProps[2]);
            //실 DATA BYTE 수
            compileField(3, ""+REAL_BYTE, this.al_FieldProps[3]);

            al_Field.set(4, fileData);

            //메시지 종료 문자
            al_Field.set(5, eom);

            //<< 전문 완성
            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 int getInformalFieldSendData(int idx, byte[] data) {
        int fldLen = getCalculatedLength(idx);
        try {
            if (idx >= this.getFieldCount() ) {
                logger.debug("{}  getInformalFieldSendData> " +idx+ " 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 (data.length < fldLen) {
                logger.debug("{}  getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader);
                String[] msgArgs = new String[2];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                msgArgs[1] = ""+idx;
                String errCode = "BECEAIFJI014";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                return -1;
            }
            ByteArrayInputStream bin = new ByteArrayInputStream(fileData);
            bin.read(data, 0, REAL_BYTE);
            // 20060419 add by khs for 전송상태 확인
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE;
            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);

            // 로깅을 위해
            byte[] fieldData = new byte[fldLen];
            System.arraycopy(data, 0, fieldData, 0, fldLen);
            this.al_Field.set( idx, fieldData);

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

    public boolean doPostExecute() {
        try {
            if (!super.doPostExecute()) return false;

            //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;
        }
    }

    public boolean doPreExecute() {
        try {
            if (!super.doPreExecute()) return false;
            try {
				Thread.sleep(300); 
			} catch (Exception e) {
				logger.error( e.getMessage(), e);
			}
            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(){
    	return 1024;
    }

    private boolean createFile ()
    {

        fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID());
        if( fin != null ) return true;
        try {
            String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
            String fileNm  = batchDoc.getBatchMsg().getHeader().getRenamedFileName();

            if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
                fileDir = fileDir + File.separator;
            }

            String fileName = fileDir + fileNm;

            File file = new File(fileName);
            if (!file.exists()) // 파일이 없으면 리턴 False
            {
                String[] msgArgs = new String[2];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                msgArgs[1] = fileName;
                String errCode = "BECEAIFJI022";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                throw new Exception(" the File["+fileName+"] does not exist!!!");
            }
            batchDoc.getBatchMsg().getHeader().setFileSize(file.length());
            fin = new FileInputStream(file);
            BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin);
            
            return 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;
        }

    }

    private boolean setData ()
    {
        try {
            if (!createFile()) {
                logger.error("{}  file open failed", logHeader);
                return false;
            }

            SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum() + 1;

            long fileSize = batchDoc.getBatchMsg().getHeader().getFileSize();
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize();

            fileData = new byte[1008];
            REAL_BYTE = Math.min((int)(fileSize - lnCurSize),fileData.length);
            fin.read(fileData, 0, REAL_BYTE);
            if ( REAL_BYTE < fileData.length ){
                fin.close();
                BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID());
                this.setConditionTxt(TelegramKeys.EOF);
            }

            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize + REAL_BYTE);
            this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO);

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


    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
        return super.getFieldValueString(1);
    }
}