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.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.eactive.eai.rms.onl.manage.comm.server.EAIServerUI;
import com.eactive.eai.rms.onl.manage.comm.server.ServerManService;
import com.google.gson.Gson;

/**
 * <pre>
 * 1. 기능 : Engine 상태 정보
 * 2. 처리 개요 :
 *     -
 * 3. 주의사항 :
 * </pre>
 *
 * @author : vs.net
 * @version : $Revision: 1.3 $
 * @since : rts 1.0
 */
@Controller
public class EaiEngineController extends BaseController{
	
	@Autowired
	private ServerManService serverManService;

	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@RequestMapping(value= "/onl/eaiengine/process/eaiEngineStatus.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/eaiEngineStatus.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			Pageable pageable ,String command
			) throws Exception {
		
		String serverNm = DataSourceContextHolder.getDataSourceType().getName();
		String keyVal = "JMX.SERVER."+serverNm;
		
		//모니터링 프라퍼티정보 JMX IP/PORT  조회
		//jmxIP = monitoringContextDAO.getProperty(keyVal);
		String jmxIP = monitoringContext.getStringProperty(keyVal);
		String[] serverInfo = null;
		
		String url = "";
//		if(jmxIP != ""){
		if(jmxIP != null && !jmxIP.equals("")){
			serverInfo = jmxIP.split(":");
			url = "http://"+jmxIP+"/JMXWeb/JmxAgent?command="+command;
		}
		
		logger.info("call url : "+url);
		
		//서버리스트 map 생성
		Page<EAIServerUI> serverList = serverManService.selectList(pageable);
		List<EAIServerUI> serverMap = serverList.getContent();
		
		HashMap servMap = new HashMap();
		for (EAIServerUI tmp : serverMap) {
			String inst = tmp.getEaiSevrInstncName();
			String ip = tmp.getEaiSevrIp();
			String port = tmp.getSevrLsnPortName();
			if (port != null) {
				servMap.put(inst, ip + "," + port);
			}

		}
		
//		if(jmxIP == "" || url == "") {
		if(jmxIP == null || url.equals("")) {
			throw new Exception("해당서버 JMX 관련 IP/PORT 정보를 확인해주세요.");
		}
		
		String resultStr = "";
		CallAgentUtil util = new CallAgentUtil();
		resultStr = util.getAgentDataToString(url);
		
		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>>();
		
		for(int i=0; i < array.size() ; i++){
			HashMap<String, Object> map = new HashMap<String, Object>();
			JSONObject data = (JSONObject)array.get(i);
			
			String servInfo = (String)servMap.get(data.get("process"));
			if(servInfo == null)continue;
			
			String[] serverArr = servInfo.split(",");
			map.put("ip", serverArr[0]);
			map.put("port", serverArr[1]);
			
			for(Object key : data.keySet()){
				map.put(key.toString(), data.get(key));
			}
			list.add(map);
		}
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , list);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	
	@RequestMapping(value= "/onl/eaiengine/process/eaiEngineStatus.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;
    }	

}

