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

import java.lang.String;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;

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;

import java.io.File;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;

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

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

        try{

        	//파일구분 (6)+은행코드(3)+블럭번호(3)+전송일자(8)
        	//파일명 파싱해서 유효성 검사가 필요한 경우 .....
        	//해당 내용 추가할것 by kscheon
            String fName = new String ((byte[]) al_Field.get(6));
            long fSize = Long.parseLong(new String ((byte[]) al_Field.get(8)));
            batchDoc.getBatchMsg().getHeader().setFileName(fName);
            
            //파일명으로 부터 거래 구분 코드 추출
    		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 = (OutsideVO)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);

            BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
            if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){
            	logger.debug("[RECV_BI0400][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")");
            	super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_NOT_REGISTERED);
                return true;
            }
            long recLen = bJobInfo.getFileRecSize();

            batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
            
            //파일이 1024(byte)xn으로 구성되므로  

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

            File f = new File(fileFullName);
            if (f.exists() && f.length() > 0) {
                long file_size = f.length();
                if (file_size >= fSize ){               	
                    //기수신완료
                    super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED);
                    batchDoc.getBatchMsg().getBody().setCurFileSize(file_size);
                } else {
                	int seq_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize();
                	int seq_no = (int)file_size/seq_size;
                	
                	if (seq_no > 0){               	
	                	batchDoc.getBatchMsg().getBody().setCurFileSize(file_size);
	                    batchDoc.getBatchMsg().getBody().setSeqNum(seq_no);

	                    JobProcessData job = JobProcessData.getInstance();
	                    String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
	                    HashMap<String, Object> hm = job.getBatchStageData(uuid);
	                    
	                    @SuppressWarnings("unchecked")
						HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA);		//결번여부 저장..
	                    if (miss_data == null) {
	                    	miss_data = new HashMap<Integer, String>();
	                    }
	                    
	                    for (int i=0; i<seq_no; i++){
	                    	miss_data.put(new Integer(i), "1");
	                    }
		            	hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
                	} else {//수신된 데이터가 seq크기만큼 안되면 처음부터 다시..
                		batchDoc.getBatchMsg().getBody().setCurFileSize(0);
                        batchDoc.getBatchMsg().getBody().setSeqNum(0);
                	}
                }
            } else {//최초 파일 수신시
                batchDoc.getBatchMsg().getBody().setCurFileSize(0);
                batchDoc.getBatchMsg().getBody().setSeqNum(0);
            }
            batchDoc.getBatchMsg().getHeader().setFileSize(fSize);
            batchDoc.getBatchMsg().getHeader().setTotRecCnt(fSize/recLen);
        } 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 );
            setConditionTxt(TelegramKeys.ERROR);
            return false;
        }
        return true;
    }

    /**
     * 전문 Validation
     */
    public boolean doValidation()
    {
        if (!super.doValidation()) return false;
        
        String fName = new String ((byte[]) al_Field.get(6));

        if (fName == null || fName.length() <= 0) {
            super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FILENAME_ERROR);

            String[] msgArgs = new String[2];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            msgArgs[1] = fName;
            String errCode = "BECEAIFJI007";
            String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);

            return false;
        }
        return true;
    }

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
			//DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
                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=8; 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 );
            setConditionTxt(TelegramKeys.ERROR);
            return false;
        }
    }

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

}
