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

import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import com.eactive.eai.common.exception.ExceptionUtil;

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_BI0710 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
	private int INFORMALFIELD_INDEX = 10;
	private int recv_seq_no;
    private ByteArrayOutputStream bout;
    
    private File f;
    private FileOutputStream fout;
	 
    public RECV_BI0710() {
        //data 송신
    	bout = new ByteArrayOutputStream();
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        try {
            String _seq_no = new String ((byte[]) al_Field.get(8));
             recv_seq_no = Integer.parseInt(_seq_no);

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

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

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
        	
        	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[]>();
            }
            @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>();
            }
            @SuppressWarnings("unchecked")
			HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_LAST_MISS);		//마지막  결번 위치 저장
            @SuppressWarnings("unchecked")
			HashMap<String, Integer> first_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_FIRST_MISS);		//첫번째 결번
            Integer firstMiss = (Integer) first_miss_field.get(JobProcessData.PROCDATA_FIRST_MISS);
            
            int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount();
           
            logger.info("{"+logHeader+"}  doPostExecute> RECV recv_seq_no [" + recv_seq_no + "] ");
            byte[] _missing_field = new byte[miss_data.size()];
            for (int j = 0; j<miss_data.size(); j++) {        //받은 seq_no만큼만 데이터 확인	            	
                String field = (String) miss_data.get( new Integer(j) );   
                _missing_field[j] = field.getBytes()[0];    //결번이 발생한 seq만 '0' 설정	
                
                if ((recv_seq_no-1) == j && _missing_field[j] == '0' ){
                	 _missing_field[recv_seq_no-1] = '1';
                     missingCount -= 1;
                     
                     miss_data.put(new Integer(j), "1");
             		 hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
                     
                }

            }
            batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field));
            batchDoc.getBatchMsg().getBody().setMissingNmCount(missingCount);
            
                
        		
            if (firstMiss != null && firstMiss.intValue() == recv_seq_no){//첫번째 결번 필드와 현재 수신된 seq가 같으면.. file write
               	
            	if (!createFile()) {
                    return false;
                }

            	fout.write(bout.toByteArray());
            	hm.put(JobProcessData.PROCDATA_FIRST_MISS, null );
            	for (int i =0; i < _missing_field.length; i++){
            		if (_missing_field[i]=='0'){
	 	            			
            			first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(i+1)); // 첫번째 결번
            			hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field );
            			
            			last_miss_field = new HashMap<String, Integer>();
    	            	last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i+1));
    	            	hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
    	            	
    	            	for (int n = recv_seq_no; n<i; n++){//현재 받은 결번 데이터와 다음 결번 사이에 seq data를 write한다.
    	            		byte[] data = (byte[]) block_data.get(new Integer(n));
    	                    fout.write(data);
    	                    block_data.remove(new Integer(n));
    	            	}
            			break;
	            	}
            	}
       	
            }else {//같지 않으면 메모리에 저장..
            	logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader);
                if (block_data.get(new Integer(recv_seq_no-1)) == null) {
                    block_data.put(new Integer(recv_seq_no-1), bout.toByteArray());
                    hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
                }
            }
            
            logger.info("{} doPostExecute> RECV missing telegram [" + recv_seq_no + "] missing field - [" + new String(_missing_field), logHeader);
            

			//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()-1; i++) {  //결번확인 필드는 비정형 필드로 바디 로그에서 제외
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));

            if (fout != null) {
                fout.close();
            }
            
            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;
        }finally{
        	try{
	        	if (fout != null) {
	                fout.close();
	            }
        	}catch(Exception e){
        		
        	}
        }
    }
    
    /**
     * int getCalculatedLength(int idx)
     * --------------------------------------------------------------------------------------
     * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
     * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
     * SEND : 송신 길이 계산
     * RECV : 수신 길이 계산
     */
    public int getCalculatedLength(int idx) {
        if (idx >= this.getFieldCount()) {
        	logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);

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

            return -1;
        }
        if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {

            String byte_size = new String ((byte[]) al_Field.get(9)); //실 DATA Byte수
            logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader);

            try {
                return Integer.parseInt(byte_size);
            } catch(Exception e) {
                String[] msgArgs = new String[1];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                String errCode = "BECEAIFJI005";
                String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                logger.error( e.getMessage(), e);
                return -1;
            }

        } else {

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

            return -1;
        }
    }
    
    public boolean doInformalField(int idx, byte[] data, int length)
    {
        try {
            if (idx == INFORMALFIELD_INDEX) {
                bout.write(data, 0, length);

                //전송상태처리
                long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length;
                batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
            } else {
            	logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader);

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

                return false;
            }
        } catch (Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI004";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            return false;
        }
        return true;
    }

    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    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 {
            String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath();
            if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) {
                strFullPath = strFullPath + File.separator;
            }
            strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName();
            logger.info("{}  getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader);
            f = new File(strFullPath);
            fout = new FileOutputStream(f, true);   //bytes will be written to the end of the file rather than the beginning
        } 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 );
            return false;
        }
        return true;
    }

}
