package com.eactive.eai.inbound.event;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import com.eactive.eai.batch.common.BatchDirUtil;
import com.eactive.eai.batch.common.FileUtil;
import com.eactive.eai.common.routing.Process;
import com.eactive.eai.common.util.Logger;

@DisallowConcurrentExecution
public class FileEventJob implements Job {
    static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER);
	
	public void execute(JobExecutionContext context) 
	{
        String dir = context.getJobDetail().getJobDataMap().getString("DIR");
        String msg = context.getJobDetail().getJobDataMap().getString("MSG");
        
        try {
            File rootDir = new File(dir);
            if ( rootDir == null || !rootDir.isDirectory()){
            	logger.error( this.getClass().getName() + ":디렉터리 지정이 올바르지 않습니다. -" + dir);
            	return;
            }
            List<File> fileList = FileUtil.getSendFileList(rootDir);
             
            for (File file : fileList) {
            	String chkExt = BatchDirUtil.getRequestRootExt();
            	if ( !file.getName().endsWith(chkExt)){
            		continue;
            	}
            	String line = getFileContent(file);
            	if ( line == null ){
            		continue;
            	}

            	String path = file.getParent();
            	String fileName = file.getName();
            	if ( file.delete() ){
    	            @SuppressWarnings("rawtypes")
    				Class cl = Class.forName(msg);
    	            Process process = (Process)cl.newInstance();
    	            process.procFileEvent(path, fileName, line);
            	}else{
            		logger.error( this.getClass().getName() + ":체크 파일을 삭제 할 수 없습니다. -" + file.getAbsolutePath());
            	}
			}

		} catch (Exception e) {
			logger.error("FileEventJob 실행도중 에러가 발생하였습니다. -" + e.getMessage());
		}
	}
	
	private String getFileContent( File file ){
		BufferedReader fbr = null;
		try {
			fbr = new BufferedReader(new FileReader(file));
			String line = fbr.readLine();
			if ( line != null && line.endsWith("@@")){
				return line;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try {
				if ( fbr != null )
					fbr.close();
			} catch (Exception e2) {}
		}
		return null;
	}
	public void setDIR( String dir){
		return;
	}
	public void setMSG( String msg){
		return;
	}
	public void setTYPE( String type){
		return;
	}
}
