package com.eactive.eai.rms.onl.eaiengine.engine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.adapter.socket.MapComparator;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.google.gson.Gson;

import edu.emory.mathcs.backport.java.util.Collections;

@Controller
public class JmsStatusController extends BaseController {

	@Autowired
	@Qualifier("comboService")
	private ComboService comboService;

	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;

	@RequestMapping(value = "/onl/eaiengine/process/jmsStatus.view")
	private String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false) String cmd)
			throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())) {
			cmd = "";
		} else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0] + cmd;
	}

	@RequestMapping(value = "/onl/eaiengine/process/jmsStatus.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, String command, String searchEaiSevrInstncName,
			String searchName, String searchDepth) throws Exception {

		String serverNm = DataSourceContextHolder.getDataSourceType().getName();
		String keyVal = "JMX.SERVER." + serverNm;

		// 모니터링 프라퍼티정보 JMX IP/PORT 조회
		String jmxIP = monitoringContext.getStringProperty(keyVal);
		String[] serverInfo = null;

		String url = "";
		if (jmxIP != null && (!"".equals(jmxIP))) {
			serverInfo = jmxIP.split(":");
			url = "http://" + jmxIP + "/JMXWeb/JmxAgent?command=" + command;
		}

		logger.debug("call url : " + url);

		if (jmxIP == null || url.equals("")) {
			throw new Exception("해당서버 JMX 관련 IP/PORT 정보를 확인해주세요.");
		}

		String resultStr = "";
		CallAgentUtil util = new CallAgentUtil();
		resultStr = util.getAgentDataToString(url, "60000");

		JSONParser parser = new JSONParser();
		JSONObject obj = (JSONObject) parser.parse(resultStr);
		JSONArray array = (JSONArray) obj.get("list");

		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

		HashMap<String, String> filter = new HashMap<String, String>();
		if (!searchName.equals(searchEaiSevrInstncName) && !"".equals(searchEaiSevrInstncName)) {
			filter.put("process", searchEaiSevrInstncName);
		}
		if (searchName != null && !"".equals(searchName)) {
			filter.put("name", searchName);
		}
		if (searchDepth != null && !"".equals(searchDepth)) {
			filter.put("depth", searchDepth);
		}

		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]);
			JSONObject dataObj = (JSONObject) array.get(i);
			for (Object key : dataObj.keySet()) {
				map.put(key.toString(), dataObj.get(key));
			}

			boolean isInclude = true;

			if (filter.size() > 0) { // 필터링
				for (String filterKey : filter.keySet()) {
					String value = filter.get(filterKey);
					if ("depth".equals(filterKey)) { // 현재 적재건수 여부
						if ("N".equals(value)) {
							if (((Long) map.get(filterKey)) > 0) {
								isInclude = false;
							}
						} else {
							if (((Long) map.get(filterKey)) <= 0) {
								isInclude = false;
							}
						}

					} else {
						String data = (String) map.get(filterKey);
						if (data.indexOf(value) < 0) {
							isInclude = false;
						}
					}

				}
			}
			if (isInclude)
				list.add(map);
		}

		// name정렬
		String[] compareParam = { "name" };

		MapComparator comp = new MapComparator(compareParam);
		Collections.sort(list, comp);

		Map resultMap = new HashMap();
		resultMap.put("rows", list);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@RequestMapping(value = "/onl/eaiengine/process/jmsStatus.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String userId = SessionManager.getUserId(request);
		HashMap paramMap = new HashMap();
		paramMap.put("userId", userId);

		String serviceType = DataSourceContextHolder.getDataSourceType().getName();
		List<ComboVo> instanceList = null;

		if ("ISG".equals(serviceType)) {
//			instanceList = comboService.selectListComboForTable("TSEAIEP03", "EAISEVRINSTNCNAME","EAISEVRINSTNCNAME","EAISEVRINSTNCNAME <>'ALL'");
		} else {
			instanceList = comboService.getFromEAIServerWithoutAll();
		}

		// 적재건수 있음없음
		List<ComboVo> listYn_Type = comboService.getFromCode("YN_TYPE");

		Map resultMap = new HashMap();
		resultMap.put("instanceList", instanceList);
		resultMap.put("ynTypeRows", listYn_Type);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/onl/eaiengine/process/jmsStatus.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) throws Exception {

		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Gson gson = new Gson();
		String jsonStr = (String) paramMap.get("gridData");
		HashMap<String, Object>[] dataList = gson.fromJson(jsonStr, HashMap[].class);

		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String) paramMap.get("headerTitle"), String[].class);

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", dataList);
		resultMap.put("fileName", (String) paramMap.get("fileName"));
		ModelAndView modelAndView = new ModelAndView("excelView", resultMap);
		return modelAndView;
	}

}
