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

import java.io.ByteArrayOutputStream;

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_KSN25_0650 extends DefaultTelegram implements TelegramService
{
    private int     SEND_LENGTH;
    private int     REAL_SEND_LENGTH;

    /**
     * 생성자
     */
    public SEND_KSN25_0650() {
        //송신 파일 통보
    }

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

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

            //구분 : 협의메세지[NG] 종료요청[SS]
            compileField(1, "NG", this.al_FieldProps[1]);

            String procType = batchDoc.getBatchMsg().getHeader().getProcessType();
            
            //송수신구분 수신요청[RJ] 송신요청[SJ] 송신확인[SR] 목록수신[RR]
            if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) {
                compileField(2, "SJ", this.al_FieldProps[2]);
            }else{
                compileField(2, "RJ", this.al_FieldProps[2]);
            }

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

            //수신조건 미수신[E] 기수신[R] 모든[A]
            compileField(4, "E", this.al_FieldProps[4]);

            if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) {
                //년월일시분 각2자리
                compileField(5, "", this.al_FieldProps[5]);

                //종료시간
                compileField(6, "", this.al_FieldProps[6]);
            }else{
                //년월일시분 각2자리
                compileField(5, "0000000000", this.al_FieldProps[5]);

                //종료시간
                compileField(6, "9999999999", this.al_FieldProps[6]);
            }

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

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

            //응답코드
            compileField(9, this.getResolveResponseCode(), 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 getSendLength()
    {
        return REAL_SEND_LENGTH;
    }

    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 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<this.al_Field.size(); i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            batchDoc.getBatchMsg().setTelegramBody("");

            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 getResCode()
    {
        return super.getFieldValueString(9);
    }
}

