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

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.scheduler.EMSScheduler;
import com.eactive.eai.rms.onl.manage.adapter.spcftmadapter.AdapterJobInfo;
import com.eactive.eai.rms.onl.manage.adapter.spcftmadapter.AdapterSchedulerUtil;
import com.eactive.eai.rms.onl.manage.adapter.spcftmadapter.SpcfTmAdapterDao;

@Controller
public class SchedulerReloadController implements InterceptorSkipController {

	private static final Logger logger = LoggerFactory.getLogger(SchedulerReloadController.class);

	private static final String resultView = "common/loadResult";

	@Autowired
	@Qualifier("spcfTmAdapterDao")
	private SpcfTmAdapterDao spcfTmAdapterDao;

	@Autowired
	private EMSScheduler emsScheduler;

	@Autowired
	@Qualifier("scheduler")
	private Scheduler scheduler;

	@RequestMapping("/schedulerReload.do")
	public ResponseEntity<Map<String, Object>> rmsSchedulerReload(String jobName) {
		Map<String, Object> result = new HashMap<>();
		try {
			emsScheduler.reloadJob(jobName);
			result.put("status", "success");
		} catch (Exception e) {
			logger.error("", e);
		}
		return ResponseEntity.ok(result);
	}

	@RequestMapping("/adapterSchedulerReload.do")
	public ModelAndView rmsAdapterSchedulerReload(HttpServletRequest request) {
		HashMap<String, String> result = new HashMap<>();
		try {

			String jobName = request.getParameter("jobName");
			HashMap<String, AdapterJobInfo> map = null;
			try {
				map = spcfTmAdapterDao.getAdapterSchedule(new HashMap<>());
			} catch (Exception e2) {
				logger.error("", e2);
				map = new HashMap<>();
			}

			AdapterJobInfo info = map.get(jobName);

			try {
				AdapterSchedulerUtil.deleteJob(this.scheduler, jobName);

				if (info != null) {
					AdapterSchedulerUtil.addJob(this.scheduler, info);
				}
			} catch (Exception e) {
				logger.error("adapter Scheduler sync reload fail", e);
			}

			result.put("status", "success");
		} catch (Exception e) {
			logger.error("monitoring context reload fail !");
			result.put("status", "error");
		}

		return new ModelAndView(resultView, "result", result.toString());
	}
}
