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

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

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 SEND_DAC25_100 extends DefaultTelegram implements TelegramService
{
    private int     SEND_LENGTH;
    private int     REAL_SEND_LENGTH;
    private File    file;
//    private Properties      
    /**
     * 생성자
     */
    public SEND_DAC25_100() {
        //송신 파일 통보
    }

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

            String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName();
//            try {
//                if ( hdrInfo.substring(58, 61).equals("LEN")){
//                	int newLen = Integer.parseInt(hdrInfo.substring(61, 65));
//                	batchDoc.getBatchMsg().getHeader().setRecLen(newLen);
//                }
//			} catch (Exception e) {}
            //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다.
            compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]);

            //전문종별코드. 전문의 기능을 나타냄.
            compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]);

            //응답코드
            compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]);

            //업무필드
            compileField(3, "", this.al_FieldProps[3]);

            //예비
            compileField(4, "", this.al_FieldProps[4]);

            //FILE NAME
            compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]);

            //FILE SIZE
            compileField(6, ""+calculateFileSize(), this.al_FieldProps[6]);

            //송신자 ID
            compileField(7, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[7]);

            //수신자 ID
            compileField(8, hdrInfo.substring(48, 58), this.al_FieldProps[8]);

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

            //FILLER 2
            compileField(10, "", this.al_FieldProps[10]);

            //마지막 여부 - 체크 안함
            compileField(11, TelegramKeys.MAGICLINK_END, this.al_FieldProps[10]);

            /*
             *
            if (checkMoreFile()){
                compileField(11, TelegramKeys.MAGICLINK_NEXT, this.al_FieldProps[10]);
            }else{
            }
            */

            //전송종류
            compileField(12, TelegramKeys.MAGICLINK_NEW, this.al_FieldProps[12]);

            //FILLER 3
            compileField(13, "", this.al_FieldProps[13]);

            //FILLER 4
            compileField(14, "", this.al_FieldProps[14]);

            //<< 전문 완성
            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 getSendLength()
    {
        return REAL_SEND_LENGTH;
    }

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

    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로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=5; 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;
        }
    }

    private long calculateFileSize () {
        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!!!");
            }

            long sendFileSize = file.length() + TelegramKeys.MLINK_HEADER_LEN;
            this.batchDoc.getBatchMsg().getHeader().setFileSize(sendFileSize);
            return sendFileSize;

        } catch (Exception e) {
            return 0;
        }
    }

    /*
    private boolean checkMoreFile(){
        String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode();
        String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode();
        SchedulerMessageVO info;
        try{
            info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode );
            if ( info != null ) {
                return true;
            }
        } catch ( Exception e){
            return false;
        }
        return false;
    }
    */

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

