package com.eactive.eai.rms.onl.adapter.socket;

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.apache.commons.httpclient.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.data.entity.onl.server.EAIServer;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.server.EAIServerService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.eactive.eai.rms.onl.common.util.DataSetUtil;
import com.eactive.eai.rms.onl.common.vo.HostInfomationForm;
import com.eactive.eai.rms.onl.manage.adapter.adapter.AdapterManService;
import com.google.gson.Gson;

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

/**
 * <pre>
 * 1. 기능 : Socket 상태 정보
 * 2. 처리 개요 :
 *     -
 * 3. 주의사항 :
 * </pre>
 *
 * @author : vs.net
 * @version : $Revision: 1.3 $
 * @since : rts 1.0
 */
@Controller
public class SocketStatusController extends BaseController {
	private final String AGENT_PAGE_STATUS = "adapter_socket2_agent1.jsp";
	private final String AGENT_PAGE_STARTSTOP = "adapter_socket2_startstop.jsp";

	@Autowired
	private AdapterManService adapterManService;

	@Autowired
	private EAIServerService eaiServerService;

	@RequestMapping(value = "/onl/adapter/socket/socketStatus.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/adapter/socket/socketStatus.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		List listRealTimeGroup = adapterManService.selectListRealTimeGroup();

		Map resultMap = new HashMap();
		resultMap.put("realTimeGroupRows", listRealTimeGroup);

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

	@PostMapping(value = "/onl/adapter/socket/socketStatus.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<HashMap<String, Object>>> selectList(HttpServletRequest request,
			String searchType, String searchAdapterGroup, String searchRealTimeCd) {

		List<EAIServer> serverList = eaiServerService.selectEaiServerIpList();

		if (serverList.isEmpty()) {
			throw new BizException("서버리스트가 없습니다.");
		}

		List<String> urls = new ArrayList<>();
		for (EAIServer serverMap : serverList) {
			String url = "http://" + serverMap.getEaisevrip() + ":" + serverMap.getSevrlsnportname()
					+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH + AGENT_PAGE_STATUS + "?adapterType=NET"
					+ "&eaiSvrInstNm=" + serverMap.getEaisevrinstncname();
			urls.add(url);
			logger.debug(url);
		}

		HashMap<String, String> filter = new HashMap<>();
		if (searchAdapterGroup != null && !"".equals(searchAdapterGroup)) {
			filter.put("AdptrBzwkGroupName", searchAdapterGroup);
		}

		if ("ERR".equals(searchType)) {
			filter.put("Status", "false"); // 어댑터 상태
			filter.put("Starting", "STOPPED"); // 기동상태
		} else if ("24H".equals(searchType)) {
			filter.put("Param8", "1"); // 24시업무여부
		} else if ("24E".equals(searchType)) {
			filter.put("Param8", "1"); // 24시업무여부
			filter.put("Status", "false"); // 어댑터 상태
			filter.put("Starting", "STOPPED"); // 기동상태
		} else if ("GRP".equals(searchType)) {
			filter.put("Param7", searchRealTimeCd); // 24시업무명
		}

		DataSetUtil gUtil = new DataSetUtil();
		gUtil.setFilter(filter);
		List<HashMap<String, Object>> list = gUtil.flushXmlToClient(urls);

		// 어댑터 업무그룹별 정렬
		String[] compareParam = { "Status", "AdptrBzwkGroupName", "EaiSevrInstncName", "AdptrBzwkName" };

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

		return ResponseEntity.ok(new GridResponse<>(list));

	}

	@RequestMapping(value = "/onl/adapter/socket/socketStatus.json", params = "cmd=TRANSACTION_STARTSTOP")
	public ModelAndView transactionStartStop(HttpServletRequest request, String eaiInstanceName, String control,
			String adapterGroupName, String adapterName) throws Exception {

		EAIServer selectedServer = eaiServerService.getByEaiSevrInstncName(eaiInstanceName);
		
		String url = "http://" + selectedServer.getEaisevrip() + ":" + selectedServer.getSevrlsnportname()
				+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH + AGENT_PAGE_STARTSTOP;

		// cmd 는 start/stop
		NameValuePair[] postParameters = new NameValuePair[] { new NameValuePair("cmd", control),
				new NameValuePair("adapterGroupName", adapterGroupName),
				new NameValuePair("adapterName", adapterName) };

		// Agent를 호출한다.
		CallAgentUtil util = new CallAgentUtil();
		String message = util.getAgentDataToString(url, postParameters);

		Map resultMap = new HashMap();
		resultMap.put("message", message); // 전체 페이지수
		return new ModelAndView("jsonView", resultMap);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/onl/adapter/socket/socketStatus.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, String gridData,
			String header, String headerTitle, String fileName, String merge) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		Gson gson = new Gson();
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);

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

		HashMap<String, Object>[] lmerge = null;
		if (merge != null) {
			lmerge = gson.fromJson(merge, HashMap[].class);
		}

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", list);
		resultMap.put("fileName", fileName);
		resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView", resultMap);

		return modelAndView;
	}

}
