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

import java.lang.String;
import java.io.ByteArrayOutputStream;
import java.io.File;

import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.common.exception.ExceptionUtil;

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

public class RECV_DAC25_100 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
    public RECV_DAC25_100() {
        //송신 파일 통보
    }

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

        try{
            String fileName = new String ((byte[]) al_Field.get(5)).substring(0, 5);
            String fromId   = new String ((byte[]) al_Field.get(7)).trim();
            if ( !fromId.equals("") ){
            	fileName = fileName + "_" + fromId;
            }
            String endGb    = new String ((byte[]) al_Field.get(11));
            String bizCode  = fileName.substring(0,5);
            long fileSize   = Long.parseLong(new String ((byte[]) al_Field.get(6)));     //화일 size
            batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
            batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
            if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) {
                this.setConditionTxt(TelegramKeys.NOFILE);
            }
            BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode);

            try {
				int recSize = (int)bJobInfo.getFileRecSize();
				batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/recSize);
			} catch (Exception e) {
				batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
			}
            String pattern = null;
            if ( bJobInfo!= null ){
                pattern = bJobInfo.getSndrcvFileName();
            }
            String recvFileName = FileUtil.getRecvFileName(fileName, pattern, batchDoc);
            batchDoc.getBatchMsg().getHeader().setFileName(recvFileName);
            batchDoc.getBatchMsg().getHeader().setRenamedFileName(new String ((byte[]) al_Field.get(5)));

        } 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<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()));
            
            String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath();
            if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) {
                strFullPathName = strFullPathName + File.separator;
            }
            strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName();
            
            File file = new File(strFullPathName);
            if ( file.exists() ){
            	file.delete();
            }
            batchDoc.getBatchMsg().getBody().setCurFileSize(0);
            LogUtil.setLogFileStart(batchDoc);
            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(1);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
        return super.getFieldValueString(2);
    }
}
