package com.eactive.eai.rms.onl.manage.adapter.spcftmadapter;

import java.util.HashMap;

import org.apache.log4j.Logger;
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.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
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.ContainerUtil;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.service.OnlAgentUtilServiceImpl;
import com.eactive.eai.rms.onl.manage.adapter.adapterchange.AdapterChangeService;

public class AdapterSchedulerJob implements Job {
	private static final Logger logger = Logger.getLogger(AdapterSchedulerJob.class);
	
	
	@Autowired
	@Qualifier("adapterChangeService")
	private AdapterChangeService service;	

	@Autowired
	@Qualifier("onlAgentUtilService")
	private OnlAgentUtilServiceImpl onlAgentUtilService;	
	
	
	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 ;
   		}  
   		service = (AdapterChangeService)appContext.getBean("adapterChangeService");	
   		onlAgentUtilService = (OnlAgentUtilServiceImpl)appContext.getBean("onlAgentUtilService");	
        
        HashMap<String,String> dataMap = new HashMap<String,String>();
        
        for(String key : context.getJobDetail().getJobDataMap().getKeys()){
        	dataMap.put(key, context.getJobDetail().getJobDataMap().getString(key));
        }
        
        if(logger.isInfoEnabled()) logger.info("adapterInfo dataMap:"+dataMap.toString());
        
        try{
	        //등록된 스케줄러 인스턴스명
	        String adtrSvrInstNm  = dataMap.get("adtrSvrInstNm").toString();
	        if(logger.isInfoEnabled()) logger.info("현제 inst : "+ContainerUtil.getInstanceName() +", 등록된 inst : "+adtrSvrInstNm);
	    		
			if(adtrSvrInstNm == null || "".equals(adtrSvrInstNm.trim())){
				context.setResult("어댑터 스케줄러 동작 해당 인스턴스명이 등록되지 않았습니다.");
				logger.error("어댑터 스케줄러 동작 해당 인스턴스명이 등록되지 않았습니다.");
			}else{
				String instName = ContainerUtil.getInstanceName();
				if(instName != null){ //취약점소스 수정 2020.08.24
					if(ContainerUtil.getInstanceName().equals(dataMap.get("adtrSvrInstNm"))){
			      	   if("start".equals(dataMap.get("startStop"))){
			  	        	adapterStart(dataMap);
			  	       }else{
			  	        	adapterStop(dataMap);
			  	       }
			         }else{
			          	//등록된 인스턴스명이 아닐경우
			        	logger.warn("모니터 프라퍼티의 어댑터 스케줄러 인스턴스명을 확인해 주세요. rule정보에 등록 인스턴스명은 "+adtrSvrInstNm+" 입니다.");
			         }
				}
			
			}
        } catch (Exception e){
        	logger.error(e.getMessage());
        	context.setResult(StringUtils.cutting(e.getMessage(), 500, "..."));
        }
        
	}
	
	// 어댑터 Start
	public void adapterStart(HashMap<String,String> paramMap){
		try{
			
			String serverName = paramMap.get("serverName");
			String adptrBzwkGroupName = paramMap.get("adptrBzwkGroupName");
			
			for(DataSourceType d : DataSourceTypeManager.getDataSourceTypes() ) {
				DataSourceContextHolder.setDataSourceType(d);
				if(serverName.equals(d.getName())){  
					HashMap<String,Object> map = new HashMap<String,Object>();
					map.put("ADPTRBZWKGROUPNAME",adptrBzwkGroupName); 
					map.put("ADPTRUSEYN","1"); //ON 
			    	service.updateChangeAdapter(map);
			    	//리로드
			    	Command command = new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterGroupCommand",adptrBzwkGroupName);
			    	onlAgentUtilService.broadcast(command);
					

			    	if(logger.isDebugEnabled()) logger.debug("=====Start a specific socket : "+adptrBzwkGroupName + " ,serverName : "+serverName);
				}
			}
		} catch (Exception e) {
			logger.error("adapterStart error : ",e);
			//e.printStackTrace();
		}
		
	}
	
	// 어댑터 Stop
	public void adapterStop(HashMap<String,String> paramMap){
		try{
			String serverName = paramMap.get("serverName");
			String adptrBzwkGroupName = paramMap.get("adptrBzwkGroupName");
			
			 for(DataSourceType d : DataSourceTypeManager.getDataSourceTypes() ) {
				DataSourceContextHolder.setDataSourceType(d);
				if(serverName.equals(d.getName())){  
					HashMap<String,Object> map = new HashMap<String,Object>();
					map.put("ADPTRBZWKGROUPNAME",adptrBzwkGroupName); 
					map.put("ADPTRUSEYN","0"); //OFF
			    	service.updateChangeAdapter(map);
			    	//리로드
			    	Command command = new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterGroupCommand",adptrBzwkGroupName);
			    	onlAgentUtilService.broadcast(command);
			    	

			    	if(logger.isDebugEnabled()) logger.debug("=====Terminate a specific socket : "+adptrBzwkGroupName);
					
					
				}
			}
		
		} catch (Exception e) {
			logger.error("adapterStop error : ",e);
			//e.printStackTrace();
		}	
	}

}
