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

import java.io.ByteArrayOutputStream;

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 RECV_NICEC_FT01 extends DefaultTelegram implements TelegramService
{

    private int INFORMALFIELD_INDEX = 6;
    private ByteArrayOutputStream bout;

    /**
     * 생성자
     */
    public RECV_NICEC_FT01() {
        bout = new ByteArrayOutputStream();
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        return true;
    }

    /**
     * 전문 Validation
     */
    public boolean doValidation()
    {
        if (!super.doValidation()) return false;


//        //업무관리정보 유효성 확인
//        if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) {
//        }
//        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) {
//        	String bizCode = super.getFieldValueString(0).substring(3);
//        	String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
//        	BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
//        	if ( jvo != null ){
//            	batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
//            	batchDoc.getBatchMsg().getHeader().setJobCode(jvo.getMsgDstCode());
//        	}
//        }
//        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) {
//        }
//        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) {
//        }
//        else {
//            logger.info("{} 0800 telegram : unknown  Operation code received >> "+this.getOpCode(), logHeader);
//            this.setResolveResponseCode("94");
//
//            String[] msgArgs = new String[2];
//            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
//            msgArgs[1] = this.getOpCode();
//            String errCode = "BECEAIFJI008";
//            String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
//            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
//
//        }
        return true;
    }

    public boolean doInformalField(int idx, byte[] data, int length)
    {
        try {
            if (idx == INFORMALFIELD_INDEX) {
            	bout.write(data, 0, length);
                // 로깅을 위해
                byte[] fieldData = new byte[length];
                System.arraycopy(data, 0, fieldData, 0, length);
                this.al_Field.set( idx, fieldData);

            } else {
                logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader);

                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 false;
            }
        } catch (Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI004";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            return false;
        }
        return true;
    }
    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
            String strRecCnt = new String((byte[])this.al_Field.get(2)).trim();
            String strRecLen = new String((byte[])this.al_Field.get(3)).trim();
            String strLen    = new String((byte[])this.al_Field.get(5)).trim();
            long recCnt  = Long.parseLong(strRecCnt);
            int recLen   = Integer.parseInt(strRecLen);
            int fnameLen = Integer.parseInt(strLen);
            String fName = new String(bout.toByteArray()).substring(0, fnameLen);
//            //파일명으로 부터 거래 구분 코드 추출
//            int bizCodeStartIndex = 0;
//            int bizCodeEndIndex   = 0;
//            String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
//            String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
//            ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
//            for (int i=0; organList!=null && i<organList.size(); i++) {
//                OutsideVO organInfo = organList.get(i);
//                if ( institutionCode.equals(organInfo.getOsdCode()) ) {
//                    bizCodeStartIndex = organInfo.getBizCdStartIdx();
//                    bizCodeEndIndex   = organInfo.getBizCdEndIdx();
//                    break;
//                }
//            }
//            if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fName.length()) bizCodeStartIndex = 0;
//            if (bizCodeEndIndex   <= 0 || bizCodeEndIndex   >  fName.length()) bizCodeEndIndex = fName.length();
//            if (bizCodeEndIndex   < 0 &&  0  <  fName.length() + bizCodeEndIndex ) bizCodeEndIndex = fName.length() + bizCodeEndIndex;
//            String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex);
//            logger.debug("bizCodeStartIndex-->" + bizCodeStartIndex);
//            logger.debug("bizCodeEndIndex-->" + bizCodeEndIndex);
//            logger.debug("fName-->" + fName);
//            logger.debug("fName.length()-->" + fName.length());
//            logger.debug("bizCode-->" + bizCode);
//            batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);

//            BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
//
//            String pattern = null;
//            if ( bJobInfo!= null ){
//                pattern = bJobInfo.getSndrcvFileName();
//            }
//            String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, true);
            batchDoc.getBatchMsg().getHeader().setFileName(fName);
            batchDoc.getBatchMsg().getHeader().setRecLen(recLen);
            long fileSize = recCnt * recLen;
            batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
            batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt);
            
			//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;
        }
    }

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