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

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.batch.common.LogUtil;
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;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;

public class RECV_LGCNS_0640 extends DefaultTelegram implements TelegramService
{

    /**
     * 생성자
     */
    public RECV_LGCNS_0640() {
        //화일정보수신통보
    }

    BufferedInputStream bis;

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;
        try {
            String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역
            long fSize = Long.parseLong(fileInfo.substring(20, 32));     //화일 size
            if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED)
                    ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면
                checkMoreFileinDB();
            } else {

            	if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면
                    // 레코드 크기 150
                	int recLen = batchDoc.getBatchMsg().getHeader().getRecLen();
                	// 한번에 블러킹 할 건수 26
                    int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recLen );

                    // 1887600 % ( 150 * 26 )
                    if ( fSize % ( recLen * seqCnt ) != 0 ){
                    	setConditionTxt(TelegramKeys.ERROR);
                        throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다.");
                	}
                    if ( !createFile() ){
                    	setConditionTxt(TelegramKeys.ERROR);
                        throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다.");
                    }
                    
                    batchDoc.getBatchMsg().getBody().setCurFileSize(0);

                    // 1887600/150= 12584
                    int  blockSize = batchDoc.getBatchMsg().getHeader().getBlockSize(); 
                    long skipBlockCnt = fSize / ( blockSize * seqCnt * recLen); 
                	
                    if ( skipBlockCnt > 0 ){
                    	long iLoopCnt = skipBlockCnt * blockSize * seqCnt;
                    	for( int inx = 0; inx < iLoopCnt; inx++){
                    		FileUtil.readLine(bis);
                    		long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize();
                    		batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen);
                    	}
                        batchDoc.getBatchMsg().getBody().setBlockNum((int)skipBlockCnt+1);    //기 송신된 블럭 다음부터 송신
                    }else{
                    	batchDoc.getBatchMsg().getBody().setBlockNum(1);
                    }
                    
                    // 
                    int seqSize = recLen * seqCnt;  // 3900
                    int blockDataSize = blockSize * seqSize; // 390000
                    int seqNo = (int)( fSize % blockDataSize ) / seqSize;

                    int appendLen = 0;
                    try {
                    	appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN));
        			} catch (Exception e) {
        				logger.error(e.getMessage(),e);
        			}

                    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[]>();
                    }

                    for (int inx = 0; inx < seqNo; inx++) {
                    	byte[] fileData = new byte[seqSize];
						for (int jnx = 0; jnx < seqCnt; jnx++) {
			                byte[] fileLine = FileUtil.readLine(bis);
			                if ( fileLine == null ){
			                    String[] msgArgs = new String[1];
			                    msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
			                    String errCode = "BECEAIFJI029";
			                    Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+
			                    		                    "확인 바랍니다.");  
			                    String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
			                    this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
			                    logger.error( e.getMessage(), e);
			                	return false;
			                }
			                if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){
			                    Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+
			                                                "확인 바랍니다.\n" +
			                                                "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " +
			                                                "파일에서 읽은 길이[" + fileLine.length + "]");
			                    this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage());
			                    logger.error( e.getMessage(), e);
			                    return false;
			                }
			                System.arraycopy( fileLine, 0, fileData, jnx * recLen, Math.min(recLen, fileLine.length));
			                if ( appendLen > 0 ){
			                	fileData[((jnx+1) * recLen)-1] = '\n';
			                }
			                if ( appendLen > 1 ){
			                	fileData[((jnx+1) * recLen)-2] = '\r';
			                }
                    		long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize();
                    		batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen);

						}

						block_data.put( new Integer(inx), fileData);
					}
                    batchDoc.getBatchMsg().getBody().setSeqNum(seqNo);

                } else { //최초 송신이면
                    batchDoc.getBatchMsg().getBody().setBlockNum(0);
                    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);
            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<9; i++) { //CMS전문의 헤더는 응답코드까지 임.
                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=9; 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);
            return false;
        }
    }

    private void checkMoreFileinDB(){
        this.setConditionTxt(TelegramKeys.NOFILE);
        return;

        /*
        String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode();
        String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode();
        SchedulerMessageVO info;

        try{
            info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode );
            if ( info == null ) {
                return;
            }
            String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID();
            String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID();

            //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
            SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID);

            //BatchMsgDoc 값 설정
            batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode());
            batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime());
            batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime());
            batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath());
            batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName());
            batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName());
            batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode());
            // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다.
            //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode());
            batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode());
            batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode());
            batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize());
            batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize());
            batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize());
            batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID());
            batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW());
            batchDoc.getEAIBatchMessage().getHeader().setFileSize(0);
            batchDoc.getEAIBatchMessage().getBody().setCurFileSize(0);
            this.setConditionTxt(TelegramKeys.EOF);

        } catch ( Exception e){

        }
        */
    }

    private boolean createFile ()
    {

        bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID());
        if( bis != null ) return true;
        try {
            String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
            String fileNm  = batchDoc.getBatchMsg().getHeader().getRenamedFileName();

            if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
                fileDir = fileDir + File.separator;
            }

            String fileName = fileDir + fileNm;

            File file = new File(fileName);
            if (!file.exists()) // 파일이 없으면 리턴 False
            {
                String[] msgArgs = new String[2];
                msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
                msgArgs[1] = fileName;
                String errCode = "BECEAIFJI022";
                String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
                this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
                throw new Exception(" the File["+fileName+"] does not exist!!!");
            }
            bis = new BufferedInputStream ( new FileInputStream(file) );
            BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis);
            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);
            return false;
        }
    }

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