package com.eactive.eai.rms.bap.manage.work.file;

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.context.ApplicationContext;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.TypeCastUtils;
import com.eactive.eai.rms.common.util.TypeCastUtils.TypeCastException;
import com.eactive.eai.rms.onl.common.service.AgentUtilService;

public class BapFileDeleteCommandJob implements Job {

	private final Logger logger = Logger.getLogger(BapFileDeleteCommandJob.class);
	private final String logPrefix = BapFileDeleteCommandJob.class.getSimpleName() + "] ";

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {

		try {
			
			DataSourceContextHolder.setDataSourceType(
					DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAP));
			
			ApplicationContext applicationContext = 
					TypeCastUtils.cast(context.getScheduler().getContext().getOrDefault("applicationContext", null), ApplicationContext.class);
			
			AgentUtilService agentUtilService = 
					TypeCastUtils.cast(applicationContext.getBean("bapAgentUtilService"), AgentUtilService.class);
			
			//CommonCommand command = new CommonCommand(DateChangeCommand.class.getName(), "ALL");
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.fileManager.DeleteFileCommand","");
			HashMap<String, Object> resultMsg = agentUtilService.broadcast(command);
			
			for(String key : resultMsg.keySet()) {
				if(String.valueOf(resultMsg.get(key)).equals("success")) {
					logger.warn(logPrefix + "Send command succeed. Instance name : " + key);
				} else {
					logger.warn(logPrefix + "Send command failed. Instance name : " + key);
				}
			}

		} catch (TypeCastException te) {
			logger.error(te.getMessage(), te);
		} catch (SchedulerException se) {
			logger.error(se.getMessage(), se);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			logger.info(logPrefix + " END]----------");
		}

	}

}
