package com.eactive.eai.rms.onl.common.service;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.ItsmSmsSender;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;

@SuppressWarnings({"rawtypes", "unchecked"})
public class EaiCmReflectionJob implements Job {
	
	private static final Logger logger = Logger.getLogger(EaiCmReflectionJob.class);

	private MonitoringContext monitoringContext; 
    private EaiCmReflectionService eaiCmReflectionService;    
    public AgentUtilService agentUtilService;
	
	private String downloadPath;
	private String backupPath;
	private String afterPath;
	//private String failPath;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
        //JobKey jobKey = context.getJobDetail().getKey();

		ApplicationContext appContext = null;
		try {
			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error",e);
			return ;
		}  
		monitoringContext  = (MonitoringContext) appContext.getBean("monitoringContext");
		eaiCmReflectionService = (EaiCmReflectionService) appContext.getBean("eaiCmReflectionService");
		agentUtilService       = (AgentUtilService) appContext.getBean("onlAgentUtilService");
		
		try {
			if (SystemUtil.isDevServer()) {
				logger.info("EaiCmReflectionJob: 해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
				return;
			}
			Properties prop = monitoringContext.getProperties();
			downloadPath   = prop.getProperty(MonitoringContext.CM_DOWNLOAD_PATH , "/dat/eaiData/engineData/download/");
			backupPath     = prop.getProperty(MonitoringContext.CM_BACKUP_PATH   , "/dat/eaiData/engineData/backup/");
			afterPath      = prop.getProperty(MonitoringContext.CM_AFTER_PATH    , "/dat/eaiData/engineData/after/");
			//failPath      = prop.getProperty(MonitoringContext.CM_FAIL_PATH    , "/dat/eaiData/engineData/fail/");
			
			run();
			
		} catch (Exception e) {
			logger.error("EaiCmReflectionJob: property module error", e);
			throw new JobExecutionException(e);
		}
		
	}
	
	private void run() throws Exception {
		
		File downloadDir = new File(downloadPath);
		
		File[] cmDirs = downloadDir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File f) {
				boolean ret = false;
				ret = f.isDirectory();
				if (ret) {
					ret = f.getName().endsWith("_TXT");
				}
				return ret;
			}
		});
		
		if (cmDirs == null || cmDirs.length == 0) {
			logger.info("$$ 로드할  CM LIST가 없음");
			return;
		}
		
		logger.info("CM LIST COUNT: "+ cmDirs.length);
		
		for (File cmDir : cmDirs) {
			
			// 1. 예약시간 체크
			String[] info = cmDir.getName().split("_");
			String runTime = info[0];
			String serviceType = info[2];
			
			if (System.currentTimeMillis() < DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", runTime)) {
				logger.info("아직 예약 CM 시간에 도달하지 않았습니다. - 대상 폴더명: "+ cmDir.getName());
				continue;
			}
			
			// 2. 파일 적재
			DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
			
			if (dt == null){
				logger.info("not support serviceType : "+ serviceType);
				continue;
			}
			
			DataSourceContextHolder.setDataSourceType(dt);
			logger.info("EaiCmReflectionJob DataSourceType = "+dt);
			File[] typeDirs = cmDir.listFiles();
			
			try{
				//DB 적재하는 부분
				HashMap<String,ArrayList<String>> syncData = new HashMap<String,ArrayList<String>>();
				
				if(typeDirs != null) {
					syncData = eaiCmReflectionService.insertFileData(dt,typeDirs);
				}
	
				//메모리 동기화 부분
				for(String key : syncData.keySet()){
					if (FileWriteUtil.INTERFACE.equals(key)){
						eaiCmReflectionService.interfaceMemorySync(syncData.get(key),syncData.get(key+"EXT"));
					} else if (FileWriteUtil.B2B.equals(key)){
						eaiCmReflectionService.b2bMemorySync(syncData.get(key));
					} else if (FileWriteUtil.C2R.equals(key)){
						eaiCmReflectionService.c2rMemorySync(syncData.get(key));
					} else if (FileWriteUtil.ADAPTER.equals(key) || FileWriteUtil.MESSAGEKEY.equals(key)) {
						//메모리동기화 화면 안됨==> 어댑터 메시지키 만 동기화
						eaiCmReflectionService.adapterMemorySync(syncData.get(key));
					}
				}
				
				// 5. after 경로로 이동
		    	//after folder check & move
		    	File afterFolder = new File(afterPath + File.separator + cmDir.getName());
		    	logger.info("afterFolder : " + afterFolder.getAbsolutePath());
		    	
		    	if (afterFolder.exists()){
		    		File backupFolder = new File(backupPath+ File.separator + cmDir.getName() + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
		    		logger.info("backupFolder : " + backupFolder.getAbsolutePath());
		    		if (backupFolder.exists() && backupFolder.isDirectory()){
		    			FileUtils.deleteDirectory(backupFolder);
		    		}
		    		afterFolder.renameTo(backupFolder);
		    	}
		    	
		    	//download folder to after folder 
		    	File downloadFolder = new File(downloadPath + File.separator + cmDir.getName());
		    	logger.info("downloadFolder : " + downloadFolder.getAbsolutePath());
		    	
		    	if (downloadFolder.exists()){
		    		downloadFolder.renameTo(new File(afterPath + File.separator + cmDir.getName()));
		    	}
		    	
			} catch(Exception e) {
				
				String sms_ip = monitoringContext.getStringProperty(MonitoringContext.ITSMPERM_IP,"");
	    		String sms_port = monitoringContext.getStringProperty(MonitoringContext.ITSMPERM_PORT,"");

	    		HashMap<String, String> map = new HashMap();
	    		map.put("ItsmPermIP", sms_ip);
	    		map.put("ItsmPermPORT", sms_port);
	    		
				String message = "EAI CM Error " + cmDir.getName();
				ItsmSmsSender.sendGroupSMS(map, ItsmSmsSender.EAI_GRP_MODE, ItsmSmsSender.EAI_GRP_MODE, message);
				logger.error(message ,e);
				
				//에러 시 fail 폴더로 이동
//				File errFolder = new File(failPath);
//				if(!errFolder.exists()){
//					errFolder.mkdir();
//				}
//				
//				File downloadFolder = new File(downloadPath + File.separator + cmDir.getName());
//		    	logger.info("downloadFolder : " + downloadFolder.getAbsolutePath());
//		    	if (downloadFolder.exists()){
//		    		downloadFolder.renameTo(new File(failPath + File.separator + cmDir.getName()));
//		    	}
			}
		}
	}
}
