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

import java.io.ByteArrayOutputStream;
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.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_SKT01_0800 extends DefaultTelegram implements TelegramService
{
    //>> 업무관리정보
    private final String OpCode_start       = "001";    //업무개시
    private final String OpCode_end         = "002";    //업무종료
    private final String OpCode_line        = "301";    //회선테스트


    /**
     * 생성자
     */
    public RECV_SKT01_0800() {
    	//개시/종료 전문
    }

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

            String fName = new String ((byte[]) al_Field.get(4));

            //파일명으로 부터 거래 구분 코드 추출
    		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);

            BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
            if ( bJobInfo != null ){
                batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getMsgDstCode());
                batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize());
            }else{
            	batchDoc.getBatchMsg().getHeader().setRecLen(100);
            }


            batchDoc.getBatchMsg().getHeader().setFileName(fName);

        } 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;

        //업무관리정보 유효성 확인
        if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) {
            logger.info("{} BATCH JOB : start request received", logHeader);
        }
        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) {
            logger.info("{} BATCH JOB : end request received", logHeader);
        }
        else if(this.getOpCode().equalsIgnoreCase(this.OpCode_line)) {
            logger.info("{} BATCH JOB : line check request received", logHeader);
        }
        else {
            logger.info("{} 0800 telegram : unknown  Operation code received >> "+this.getOpCode(), logHeader);
            this.setResolveResponseCode("99");

            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 doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
			//DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<11; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

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


}
