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

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

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

public class SEND_SKT01_2100 extends DefaultTelegram implements TelegramService
{

	private FileInputStream fin ;
    private int BLOCK_NO;
    private int SEQUENCE_NO;
    private int REAL_BYTE;      // 실 data byte수
    private int DATA_LEN;
    private int SEND_LENGTH;    //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
    private int REAL_SEND_LENGTH;  //실제 송신할 전문의 총길이

    private Properties telegramInfo;
    private byte[] fileData;

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

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

            //전송길이
            compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]);

            //TRANSACTION CODE
            compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]);


            //송신기관코드 - 송신기관코드 참조 "7170"
            compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]);

            //전문코드(개시/데이터/결번)
            compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);

            //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8)
            compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]);

            //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.)
            compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]);

            //전송일자(YYMMDD)
            compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]);

            //전송시각(HH24MISS)
            compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]);

            //응답코드
            compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]);
            //암호 - UNUSED

            compileField(9, "", this.al_FieldProps[9]);

            //RESERVED - UNUSED
            compileField(10, "", this.al_FieldProps[10]);

            //BLOCK-NO
            compileField(11, ""+BLOCK_NO, this.al_FieldProps[11]);

            //RECORD 일련번호
            compileField(12, ""+SEQUENCE_NO, this.al_FieldProps[12]);

            //DATA ( 총 길이 + DATA건수 + 1개 DATA 길이 + DATA + SPACE  
            compileField(13, new String(fileData), this.al_FieldProps[13]);

            //<< 전문 완성
            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;
            }
            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=0; i<11; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=11; i< al_Field.size()-1; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            baout.write((byte[])this.al_Field.get(al_Field.size()-1), 0, 12);
            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;
        }
    }
    
    /**
     * int getCalculatedLength(int idx)
     * --------------------------------------------------------------------------------------
     * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
     * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
     */
    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)) {
            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 ()
    {
    	
    	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!!!");
            }
            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 setBlockAndSeqNO ()
    {
        int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
        if ( missing_count > 0 ){
        	return setBlockAndSeqNO_from_memory();
        }else{
        	return setBlockAndSeqNO_from_disk(); 
        }

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

            int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize();
            int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum();
            int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum();
            
            if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면
                this.BLOCK_NO = 1;
                this.SEQUENCE_NO = 1;
                this.setConditionTxt("");

            } else {
                if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송
                    this.BLOCK_NO = block_no+1;
                    this.SEQUENCE_NO = 1;
                    this.setConditionTxt("");

                } else if (seq_no >= block_size-1) {    //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함
                    this.BLOCK_NO = block_no;
                    this.SEQUENCE_NO = seq_no+1;
                    this.setConditionTxt(TelegramKeys.BLOCKEND);
                } else {            //한 블럭내에 데이터 전송 반복이면
                    this.BLOCK_NO = block_no;
                    this.SEQUENCE_NO = seq_no+1;
                    this.setConditionTxt("");
                }

            }
            // 한번에 블러킹 할 건수
            int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() );
            // 남은 바이트 수
            long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize();
            // 남은 건수
            long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen();
            logger.debug("[SEND_0320]remainCnt-->" + remainCnt);
            
            boolean isLastSeq = false;
            if ( seqCnt < remainCnt ){
            	DATA_LEN = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen();
            }else{
            	DATA_LEN = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen();
            	this.setConditionTxt(TelegramKeys.BLOCKEND);
            	isLastSeq = true;
            }
            int readCnt = DATA_LEN / batchDoc.getBatchMsg().getHeader().getRecLen();
            
            fileData = new byte[4004];
            for (int inx1 = 0; inx1 < fileData.length; inx1++) {
				fileData[inx1] = ' ';
			}
            String strDataTotLen = makeZero("" + ( DATA_LEN + 19),4);
            String strRecCount = makeZero( "" + readCnt, 4);
            String strRecLen = makeZero( "" + batchDoc.getBatchMsg().getHeader().getRecLen(), 4);
            System.arraycopy( strDataTotLen.getBytes(), 0, fileData, 0, 4);
            System.arraycopy( strRecCount.getBytes(), 0, fileData, 4, 4);
            System.arraycopy( strRecLen.getBytes(), 0, fileData, 8, 4);
            
            byte[] fileLine = null;
            for ( int inx = 0 ; inx < readCnt ; inx++){
                fileLine = FileUtil.readLine(fin);
                System.arraycopy( fileLine, 0, fileData, 12 + inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen());
                if ( BLOCK_NO == 1 && SEQUENCE_NO == 1 && inx == 0 ){
                	batchDoc.getBatchMsg().setFileHeader(new String(fileLine));
                }
            }
            
            if ( isLastSeq ){
            	batchDoc.getBatchMsg().setFileTrailer(new String(fileLine));
            	fin.close();
            	BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID());
            }
            
            // 20060419 add by khs for 전송상태 확인
            long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + DATA_LEN;
            batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
        	
            // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한
            JobProcessData job = JobProcessData.getInstance();
            String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
            HashMap<String, Object> hm = job.getBatchStageData(uuid);

            @SuppressWarnings("unchecked")
			HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
            if (block_data == null) {
                block_data = new HashMap<Integer, byte[]>();
            }
            block_data.put( new Integer(SEQUENCE_NO-1), fileData);
            hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
            // 2008.06.19 - 정동한
            
            this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO);
            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;
        }
    }
    
    private boolean setBlockAndSeqNO_from_memory ()
    {
        try {

            int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum();

            int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
            String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField();
            int missing_fld_len = missing_field.getBytes().length;
            byte[] _missing = missing_field.getBytes();

            this.BLOCK_NO = block_no;

            for (int i=0; i<missing_fld_len; i++) { //missing_filed의 길이는 block_size와 동일
                if(_missing[i] == '0') {
                    this.SEQUENCE_NO = i+1;
                   _missing[i] = '1';
                   missing_count -= 1;
                    break;
                }
            }
            
            if ( missing_count == 0 ){
            	this.setConditionTxt(TelegramKeys.BLOCKEND);
            }
            this.batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing));
            this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missing_count);
            
        	String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
            JobProcessData job = JobProcessData.getInstance();
            HashMap<String, Object> hm = job.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("SENDED FILE DATA IS NULL"));
                String[] msgArgs = new String[1];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                String errCode = "BECEAIFJI026-1";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                return false;
            }
            fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) );
            this.REAL_BYTE = fileData.length;

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

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


}

