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

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

import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;

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_BI0410 extends DefaultTelegram implements TelegramService
{
	private BufferedInputStream bis;
	/**
     * 생성자
     */
    public RECV_BI0410() {
//    	화일정보수신보고
    }

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

        if (!createFile()) {
            logger.error("{}  file open failed", logHeader);
            setConditionTxt(TelegramKeys.ERROR);
            return false;
        }
        
        try{
        	long rSize = Long.parseLong(new String ((byte[]) al_Field.get(8)));

            if (getResCode().equalsIgnoreCase(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED)) { //기송신 파일이면
                this.setConditionTxt(TelegramKeys.COMPARE);

            } else {
                int seqSize = batchDoc.getBatchMsg().getHeader().getSequenceSize();

                int totSeqSizeOffSize = 0;

                if (rSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){
                	logger.debug("{"+logHeader+"} doExecute ]  recive file size is bigger than current file size ");
                	this.batchDoc.getBatchMsg().getBody().setErrorMsg("RECV_BI0410 - doExecute ]  recive file size is bigger than current file size");
                    setConditionTxt(TelegramKeys.ERROR);
                	return false;
                }
                if (rSize > 0) { //기 송신된 파일이면서 미완료 파일이면
                    totSeqSizeOffSize = (int)(rSize / seqSize);
                    if (totSeqSizeOffSize > 0 ) {   //
                     
                        batchDoc.getBatchMsg().getBody().setSeqNum(totSeqSizeOffSize);
                        batchDoc.getBatchMsg().getBody().setCurFileSize(rSize);
                        byte[] fileData = new byte[seqSize];
                        for (int i=0; i<totSeqSizeOffSize; i++){
                        	bis.read(fileData);
                        	
//                          파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 
                            JobProcessData job = JobProcessData.getInstance();
                            String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
                            HashMap<String, Object> hm = job.getBatchStageData(uuid);

                            @SuppressWarnings("unchecked")
							HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
                            if (block_data == null) {
                                block_data = new HashMap<Integer, byte[]>();
                            }
                            block_data.put( new Integer(i) ,  fileData);
                            hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
                        } 
                    }
                    else {//기전송된 파일의 사이즈가 seqSize보다 작으면 처음부터 다시 송신
                        batchDoc.getBatchMsg().getBody().setSeqNum(0);
                    }
                } else { //최초 송신이면
                    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 );
            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;
        }

//        String filegbn = fName.substring(0, 6).trim();
//        String fbankcd = fName.substring(6, 9).trim();
//        int fblockno = Integer.parseInt(fName.substring(9, 12));
//        String senddate = fName.substring(12, 20);

        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()));

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

    
    private boolean createFile ()
    {

    	try {
    		bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() );

    		if (bis == null){
        		logger.warn("FILE정보가 NULL입니다.");
                return false;
            }
            return true;
        } catch (Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI028";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( e.getMessage(), e );
            setConditionTxt(TelegramKeys.ERROR);
            return false;
        }

    }
}
