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

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

import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.batch.common.LogUtil;
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_KSDBT_0200 extends DefaultTelegram implements TelegramService
{

	private BufferedInputStream bis;
    private File file;
    private int SEQUENCE_NO;
    private int LAST_SEQ;       //일련번호
    private int REC_CNT;
    private int REAL_BYTE;      // 실 data byte수
    private int SEND_LENGTH;    //실제 송신할 전문의 총길이
    private boolean isReSend = false;

    private Properties telegramInfo;
    private byte[] fileData;
    private int retryCnt;

    /**
     * 생성자
     */
    public SEND_KSDBT_0200() {
        //DATA전문
    }

    /**
     * 전문조립
     */
    public boolean doExecute() {
        try {
            boolean result = makeSendData();
            if (!result) {
                return false;
            }
            result = calculateSendLength();
            if (!result) return false;

            //송신전문의 총 Byte 수
            compileField(0, String.valueOf(SEND_LENGTH), this.al_FieldProps[0]);
            //TR CODE
            compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]);
            //기관 ID
            compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]);
            //전문종별코드
            compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
            //통신망관리정보
            //001-업무개시, 002-재개시, 040-종료, 301-회선시험
            compileField(4, this.getFldOpCode(), this.al_FieldProps[4]);
            //데이터전문코드
            compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]);
            //응답코드
            compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]);
            //전문전송일시
            compileField(7, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[7]);
            //전문일련번호
            compileField(8, "" + SEQUENCE_NO, this.al_FieldProps[8]);
            compileField(9, "" + REC_CNT, this.al_FieldProps[9]);

            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() ) {
                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) {
                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;

            if ( file != null ){ // 처음 전송이면
                LogUtil.setLogFileStart(batchDoc);
            }
//            if ( this.getOpCode().equals("000") ){ // DATA전송인 경우
////                this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO + REC_CNT - 1);
//            }
//            if ( this.getFldOpCode().equals("999") ) { //DATA를 보낸 후 보낸 SEQ RESET
////                batchDoc.getBatchMsg().getHeader().setSequenceSize(0);
////                batchDoc.getBatchMsg().getHeader().setBlockSize(0);
//            }

            //DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임.
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=10; 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;
            isReSend = false;
            String prevTelegramHeader = batchDoc.getBatchMsg().getTelegramHeader();
            String prevTelegramType = "";
            String prevTelegramRescd = "";
            String prevTelegramSeqNo = "";

            if ( prevTelegramHeader.length() >= 49 ){
                prevTelegramType  = prevTelegramHeader.substring(18, 22);
                prevTelegramRescd = prevTelegramHeader.substring(35, 37);
                prevTelegramSeqNo = prevTelegramHeader.substring(51, 59);
            }

            if ( prevTelegramType.equals("0200")){ /// TIMEOUT이후 재전송이면
                retryCnt = 1;
                batchDoc.getBatchMsg().getBody().setErrorMsg("");
            }else{
                //1. 데이터 수신 일련번호 에러인 경우
                if ( prevTelegramRescd.equals("01") || prevTelegramRescd.equals("02") ) {
                    isReSend = true;
                    LAST_SEQ = Integer.parseInt(prevTelegramSeqNo);

                    retryCnt = 0;
                }
            }
            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 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;
        }
    }

    /**
     * int getCalculatedLength(int idx)
     * --------------------------------------------------------------------------------------
     * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
     * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
     */
    public int getCalculatedLength(int idx) {

        if (idx >= this.getFieldCount()) {
            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)) {
            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;
        }
        return REAL_BYTE;

    }

    private boolean createFile ()
    {
    	bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() );

        if ( bis == null ){
            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 = 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!!!");
                }
                bis = new BufferedInputStream ( new FileInputStream(file) );
                BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis);
            } 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 !( bis == null);
    }

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

            if ( retryCnt > 0 ){  // 타임오버 이후의 재 전송인 경우, 이전에 DATA가 있었던 경우에만
                if ( batchDoc.getBatchMsg().getTelegramBody() != null && !batchDoc.getBatchMsg().getTelegramBody().equals("") ){
                	fileData = batchDoc.getBatchMsg().getTelegramBody().getBytes();
                }
            }else{
                if ( isReSend ){ // 중단된 이후 재 송신인 경우
                    skipLine();
                }

                // 레코드 크기
                int recSize = batchDoc.getBatchMsg().getHeader().getRecLen();
                // 한번에 블러킹 할 건수
                int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize );
                // 남은 바이트 수
                long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize();
                // 남은 건수
                long remainCnt = remainSize / recSize;
                logger.debug("[SEND_KSDBT_0200]seqCnt   -->" + seqCnt);
                logger.debug("[SEND_KSDBT_0200]remainCnt-->" + remainCnt);
                if ( seqCnt < remainCnt ){
                	REC_CNT = seqCnt;
                }else{
                	REC_CNT = (int)remainCnt;
                }
                REAL_BYTE = REC_CNT * recSize;
                fileData = new byte[REAL_BYTE];
                for ( int inx = 0 ; inx < REC_CNT ; inx++){
                    byte[] fileLine = FileUtil.readLine(bis);
                    if ( file != null && inx == 0 ){
                    	batchDoc.getBatchMsg().setFileHeader(new String(fileLine));
                    }
                    if ( inx == REC_CNT -1 ){
                    	batchDoc.getBatchMsg().setFileTrailer(new String(fileLine));
                    }
                    System.arraycopy( fileLine, 0, fileData, inx * recSize, recSize);
                    byte[] seqArea = new byte[8];
                    System.arraycopy( fileLine, 0, seqArea, 0, 8 );
                    try {
                        SEQUENCE_NO = Integer.parseInt( new String(seqArea));
					} catch (Exception e) {
	                    SEQUENCE_NO = 0;
					}
                }
            }

            if ( REAL_BYTE == 0 ){
                this.setFldOpCode("999");
                bis.close();
                SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum();
                BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() );
            }

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

    private void skipLine() throws Exception{
        byte[] fileLine = null;
        byte[] byte_sequence = new byte[8];
        int iSequence = 0;
        while ( ( fileLine = FileUtil.readLine(bis) ) != null ){
            System.arraycopy( fileLine, 0, byte_sequence, 0, 8);
            iSequence = Integer.parseInt( new String(byte_sequence));
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen();
            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
            if ( LAST_SEQ == iSequence )
            	return;
        }
        throw new Exception("재전송 시작할 위치를 찾지 못하였습니다.");
    }

    private boolean calculateSendLength () {
        try {
            for (int i=0; i< this.al_Field.size()-1; i++) {
                byte[] aField = (byte[]) this.al_Field.get(i);
                SEND_LENGTH += aField.length;
            }
            SEND_LENGTH += REAL_BYTE;
        } 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;
    }

    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
        return super.getFieldValueString(3);
    }
    // 거래구분코드 필드값 리턴
    public String getTrClass()
    {
        return super.getFieldValueString(4).substring(3);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(6);
    }
    //업무관리코드 필드값 리턴
    public String getOpCode()
    {
        return super.getFieldValueString(4);
    }
}

