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


import java.util.HashMap;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;

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.CommonUtil;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.eactive.eai.rms.onl.eaiengine.engine.QueueMonitoringService;

public class QueueMonitoringJob implements Job{
    /**
    * Logger for this class
    */
	
    private static final Logger logger = Logger.getLogger(QueueMonitoringJob.class);
    
    private transient MonitoringContext monitoringContext;
    
	
	@Autowired
	@Qualifier("queueMonitoringService")
	private QueueMonitoringService queueMonitoringService;
    
    
	// 특정시간 주기적으로 jms Queue 모니터링 DB 적재 스케줄러
    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
    	
    	if(logger.isInfoEnabled()) logger.info("START QueueMonitoringJob");
    	
//        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");	
		queueMonitoringService = (QueueMonitoringService)appContext.getBean("queueMonitoringService");
   		
   		String serverNm = "";
		String jmxIP = null;
		String timeOutSet = monitoringContext.getStringProperty(MonitoringContext.JMX_SET_TIMEOUT);
		//등록시간
		String regDate = CommonUtil.getToday("");
		regDate += "000";
			
   		try {
   			for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
				if(logger.isInfoEnabled()) logger.info("DataSourceTypeManager d : "+d);
				if(d.getName().equals("ISG")) continue; //일괄제외 

				DataSourceContextHolder.setDataSourceType(d);
	   			serverNm = DataSourceContextHolder.getDataSourceType().getName();
	   			
	   			//모니터링 프라퍼티정보 JMX IP/PORT  조회
	   			jmxIP = getMonitoringProperty(serverNm);
	   			
	   			String[] serverInfo = null;
	   			String url = "";
	   			
	   			if(jmxIP != null){
	   				serverInfo = jmxIP.split(":");
	   				url = "http://"+jmxIP+"/JMXWeb/JmxAgent?command=destination";
	   			}else{
	   				logger.warn(d.getName()+" JMX url error ");
					continue;
	   			}
	   			
	   			if(logger.isInfoEnabled()) logger.info("destination call url : "+url);
	   			
	   			String resultStr = null;
	   			CallAgentUtil util = new CallAgentUtil();
	   			try {
	   				//timeout 수정
					resultStr = util.getAgentDataToString(url,timeOutSet);
				} catch (Exception e) {
					logger.warn("서버의 Agent 호출 결과 리턴 실패", e);
				}
	   			
	   			if(resultStr == null){
					continue;
	   			}
	   			
	   			JSONParser parser = new JSONParser();
	   			JSONObject obj = (JSONObject)parser.parse(resultStr);
	   			JSONArray array = (JSONArray)obj.get("list");
	   			
	   			if(array.size() == 0 || array == null){
	   				logger.warn(d.getName()+" 서버의 JMS Queue 정보가 없습니다");
					continue;
	   			}
	   			
	   			for(int i=0; i < array.size() ; i++){

	   				HashMap<String, Object> map = new HashMap<String, Object>();
	   				map.put("ip", serverInfo[0]);
	   				map.put("port", serverInfo[1]);
	   				map.put("regDate", regDate);
	   				
	   				JSONObject dataObj = (JSONObject)array.get(i);
	   				for(Object key : dataObj.keySet()){
	   					Object o = dataObj.get(key);
	   					if(o instanceof Boolean) {
	   						map.put(key.toString(), Boolean.toString((Boolean)o));
	   					}
	   					else {
	   						map.put(key.toString(), dataObj.get(key));
	   					}
	   				}
	   				//EMS 모니터링 TSEAIRM30 INSERT
	   				try{
		   				queueMonitoringService.insert(map);
		   			} catch (Exception e) {
						logger.warn("TSEAIRM30 insert fail ", e);
					}
	   				
	   			
	   			}
		   			
   			}
   			
   		} catch (Exception e) {
   			logger.error("QueueMonitoringJob error : ",e);
		}  
				
	}
    
    public String getMonitoringProperty(String serverNm) {
    	
    	String serverIp = null;
    	
    	if("DSG".equals(serverNm)){
    		serverIp = monitoringContext.getStringProperty(MonitoringContext.JMX_SERVER_DSG);
    	}else if("GSG".equals(serverNm)){
    		serverIp = monitoringContext.getStringProperty(MonitoringContext.JMX_SERVER_GSG);
    	}else if("NSG".equals(serverNm)){
    		serverIp = monitoringContext.getStringProperty(MonitoringContext.JMX_SERVER_NSG);
    	}else if("ZSG".equals(serverNm)){
    		serverIp = monitoringContext.getStringProperty(MonitoringContext.JMX_SERVER_ZSG);
    	}else if("ASG".equals(serverNm)){
    		serverIp = monitoringContext.getStringProperty(MonitoringContext.JMX_SERVER_ASG);
    	}
    	
    	if(logger.isInfoEnabled()) logger.info("serverNm >>> "+serverNm+" serverIp >>> "+serverIp);
		return serverIp;
    	
    }
	
	
}
