package com.eactive.eai.adapter.db.sql;

import com.eactive.eai.adapter.db.DBAdapterKeys;
import com.eactive.eai.common.util.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.utils.Key;

public class DBInboudSqlAdapterJob  implements Job {
	
	public static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	private static boolean isLocalTest = false;
	
	static {
		String isLocal = System.getProperty("isLocalTest");
		if(isLocal != null && "true".equalsIgnoreCase(isLocal)) {
			isLocalTest = true;
		}
	}
	
	private void debug(String msg) {
		if(isLocalTest) {
			System.out.println (msg);
		}
		else {
			logger.info(msg);
		}
	}
	
//	private DBInboudSqlAdapter adapter = null;
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// JobKey jobKey = context.getJobDetail().getKey();
		Key jobKey = context.getJobDetail().getKey();
		String data = "";
		for (String key : context.getJobDetail().getJobDataMap().getKeys()) {
			data = data + key + "=" + context.getJobDetail().getJobDataMap().getString(key) + ",";
		}
		debug( jobKey + " start data(" + data + ")");
		logger.warn(">> " + jobKey + " start data(" + data + ")");
		String jobKeyName = jobKey.getName();
		
		String adapterName = context.getJobDetail().getJobDataMap().getString(DBAdapterKeys.ADAPTER_NAME);
		String propGroupName = context.getJobDetail().getJobDataMap().getString(DBAdapterKeys.ADAPTER_PROPGN);
		debug("adapterName=" + adapterName + ",  propGroupName"+ propGroupName );
		
		
		DBInboudSqlAdapter adapter = DBInboudSqlAdapterManager.getInstance().get(adapterName);
		if(adapter == null) {
			debug(jobKey + " : @@@@ Adapter not found in JobDataMap");
		}
		else {
			if(adapter.isRunningState()) {
				debug(jobKey + " : Adapter already RUNNING with previous scledule");
			}
			else {
				debug(jobKey + " : Adapter Called.");
				adapter.execute();
			}
		}
	}
}
