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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;

import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.osd.OutsideVO;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_KOFCB_0630 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
    public RECV_KOFCB_0630() {
        //화일정보수신요구
    }

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

        try{

            String fileInfo = new String ((byte[]) al_Field.get(9));
            String fName = fileInfo.trim();
            String strFsize = new String ((byte[]) al_Field.get(10));
            long fSize = Long.parseLong(strFsize);     //화일 size

            //파일명으로 부터 거래 구분 코드 추출
            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();
            String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex);
            batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);

            String pattern = null;
            BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
            if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){
                logger.debug("[RECV_KOFCB_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")");
//                this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED);
            }
            
            long recLen = 0;
            if ( bJobInfo == null ){
            	batchDoc.getBatchMsg().getHeader().setRecLen(-1);
            }else{
            	pattern = bJobInfo.getSndrcvFileName();
                recLen = bJobInfo.getFileRecSize();
            	batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize());
            	batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getMsgDstCode());
            }

            String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false);
            batchDoc.getBatchMsg().getHeader().setFileName(fName);
            batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName);

            String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
            logger.debug("{}  DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader);
            if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
                fileDir = fileDir + File.separator;
            }
            String fileFullName = fileDir + recvFileName;

            File file = new File(fileFullName);
            if (file.exists() && file.length() > 0) {
                //파일 수신시에 미완료된 파일은 처음부터 받는다.  따라서 기존 파일 삭제
                file.delete();
            }
            batchDoc.getBatchMsg().getBody().setCurFileSize(0);
            batchDoc.getBatchMsg().getHeader().setFileSize(fSize);
            long recCnt = 0;
            if ( recLen > 0 ){
            	recCnt = fSize / recLen;
            }
            batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt);
            batchDoc.getBatchMsg().getBody().setBlockNum(0);
            batchDoc.getBatchMsg().getBody().setSeqNum(0);
        } 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;
        }
        return true;
    }

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

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
            //DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임.
                byte[] barr = (byte[])this.al_Field.get(i);
                if ( barr[0] != '\0') {
                    baout.write((byte[])this.al_Field.get(i));
                }
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=9; 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);
    }
    // 거래구분코드 필드값 리턴
    public String getTrClass()
    {
        return super.getFieldValueString(5);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(8);
    }
    //업무관리코드 필드값 리턴
    public String getOpCode()
    {
        return super.getOpCode();
    }
}