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

import java.io.ByteArrayOutputStream;

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

public class SEND_DAC25_007 extends DefaultTelegram implements TelegramService
{
    private int     SEND_LENGTH;
    private int     REAL_SEND_LENGTH;

    /**
     * 생성자
     */
    public SEND_DAC25_007() {
        //LOGOUT 요구
    }

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

            //길이 필드 
            compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]);

            //TR CODE 
            compileField(1, "", this.al_FieldProps[1]);

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

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

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

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

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

            //송신자 암호
            compileField(7, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[7]);

            String procType = batchDoc.getBatchMsg().getHeader().getProcessType();
            if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) {
                //Job Type
                compileField(8, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[8]);
                //File Name
                compileField(9, "", this.al_FieldProps[9]);
                //Flag
                compileField(10, "", this.al_FieldProps[10]);
                //시작시간
                compileField(11, "", this.al_FieldProps[11]);
                //끝시간
                compileField(12, "", this.al_FieldProps[12]);
            }else{
                //Job Type
                compileField(8, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[8]);
                //File Name
                compileField(9, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[9]);
                //Flag
                compileField(10, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[10]);
                //시작시간
                compileField(11, "", this.al_FieldProps[11]);
                //끝시간
                compileField(12, "", this.al_FieldProps[12]);
            }

            //FILLER
            compileField(13, "", 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 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<6; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=6; 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 String getTelegramType()
    {
        return super.getFieldValueString(2);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(3);
    }
}