package com.eactive.eai.batch.job.jobModule.Component;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.util.Properties;

import com.eactive.eai.batch.job.jobConstant.TelegramKeys;

import com.eactive.eai.batch.common.CommonKeys;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager;
import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.secure.inisafe.IniSafeManager;

public class END extends JobComponent implements JobComponentService
{

    // 소켓을 구한다.
    BatchRunningJobManager bs_man   = BatchRunningJobManager.getInstance();
    Socket             socket ;

    public BatchDoc execute() throws Exception {

    	FileInputStream fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() );
    	if ( fin != null){
    		try{
        		fin.close();
        		BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() );
            } 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);
            }
    	}

    	BufferedReader fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() );
    	if ( fbr != null){
    		try{
    			fbr.close();
        		BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() );
            } 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);
            }
    	}
    	
    	BufferedInputStream bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID());
    	if (bis != null){
    		try {
    			bis.close();
    			BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID());
    		} 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);
            }
    	}
    	//우선순위 처리를 위해 전송된 파일 수 증가와 실행여부 업데이트 
		//2009.8.19 by kscheon - start
    	if (batchDoc.getBatchMsg().getHeader().getProcessType().equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)){ //요구송신이면서 재처리 설정되어 있으면..
    		

	    	try{
	    		String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
		    	String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_" + bizCode + "}";
		
				PropManager pmanager = PropManager.getInstance();
				Properties telegramInfo = pmanager.getProperties(propName);
				String isPriority ="";
				String[] priorityList = null;
				
				if (telegramInfo != null ){
		        	isPriority = telegramInfo.getProperty("priority");
		        }
		        BatchJobPriorityManager jobpmanager = BatchJobPriorityManager.getInstance();
	        	
	        
		        //우선순위가 설정된 업무인 경우에는 같은 우선순위의 작업만 한번에 socket을 할당 할 수 있도록 한다.
		        if (isPriority != null && "Y".equals(isPriority)){
		        	String plist = telegramInfo.getProperty("priority.list");
		        	if (plist != null && plist.length() >0){//등록된 우선순위 목록이 있으면..
			        	
		        		priorityList = plist.split(",");
		        	}
		        	
		        	if (priorityList != null && priorityList.length >0){
			    		BatchJobPriorityVO datavo = jobpmanager.getPriorityDatabyBizCode(priorityList[0], batchDoc.getBatchMsg().getHeader().getBizCode());
			    						
						if (datavo != null){
							int dataCount = datavo.getDataCount();
							datavo.setDataCount(dataCount+1);
						}
			    					
						if (!bizCode.equals(priorityList[0]) 
								&& bizCode.equals(priorityList[priorityList.length-1])){ //마지막 우선순위 작업을 실행했으면.. 우선순위 목록의 마지막 작업은 우선순위가 가장 낮아야 한다.
							jobpmanager.delPriorityData(priorityList[0]);	//등록된 우선순위 목록을 삭제한다.
						}else {
							jobpmanager.updateExecuteJobList(priorityList[0],bizCode, this.batchDoc.getBatchMsg().getHeader().getUUID(), this.batchDoc.getBatchMsg().getHeader().getFileName());	
						}
					 }
			      }
	    	}catch (Exception e){
	    		//무시..
	    	}
    	}
    	
    	IniSafeManager.getInstance().removeManager(batchDoc);

		//우선순위 처리를 위해 전송된 파일 수 증가와 실행여부 업데이트 
		//2009.8.19 by kscheon - end

    	logger.info("{} END.execute>> Batch job end ", logHeader);

        logger.debug("{} 1. Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader);

        return batchDoc;
    }

}
