package com.eactive.eai.rms.onl.adapter.http.httpStatus;

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.common.vo.JsonPageVo;
import com.eactive.eai.rms.common.vo.SimpleResponse;
import com.eactive.eai.rms.data.entity.onl.server.EAIServerService;
import com.eactive.eai.rms.onl.adapter.socket.MapComparator;
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.google.gson.Gson;

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

/**
 * <pre>
 * 1. 기능 :
 * 2. 처리 개요 :
 *     -
 * 3. 주의사항 :
 * </pre>
 *
 * @author : 박기섭
 * @version : $Revision: 1.13 $
 * @since : rts 1.0
 */
@Controller
public class HttpStatusController extends BaseController {
	private static final String AGENT_PAGE_STATUS = "adapter_status_agent.jsp";
	private static final String AGENT_PAGE_STARTSTOP = "adapter_startstop_agent.jsp";

	private EAIServerService eaiServerService;

	@Autowired
	protected HttpStatusController(EAIServerService eaiServerService) {
		this.eaiServerService = eaiServerService;
	}

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

	@PostMapping(value = "/onl/adapter/http/httpStatus.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<HashMap<String, Object>>> selectList(
			@RequestParam(name = "adapterType", defaultValue = "") List<String> adapterTypes,
			String searchAdapterGroup) {

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

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

		List<String> urls = new ArrayList<>();

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

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

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

		// 리스트에서 데이터가 없을때 제거
		list.removeIf(m -> m.get("adapterGroupSimple") == null || m.get("adapterGroupSimple") == "");

		// 어댑터 업무그룹별 정렬
		String[] compareParam = { "adapterStatus", "adapterGroupName", "eaiSvrInstNm" };
		MapComparator comp = new MapComparator(compareParam);
		Collections.sort(list, comp);
		return ResponseEntity.ok(new GridResponse<>(list));
	}

	@PostMapping(value = "/onl/adapter/http/httpStatus.json", params = "cmd=TRANSACTION_STARTSTOP")
	public ResponseEntity<SimpleResponse> transactionStartStop(HttpServletRequest request, String eaiInstanceName,
			String adapterType, String control, String adapterGroupName, String adapterName) throws Exception {

		EAIServer eaiServer = eaiServerService.getByEaiSevrInstncName(eaiInstanceName);

		String url = "http://" + eaiServer.getEaisevrip() + ":" + eaiServer.getSevrlsnportname()
				+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH + AGENT_PAGE_STARTSTOP;

		// cmd 는 START/STOP
		NameValuePair[] postParameters = new NameValuePair[] { new NameValuePair("adapterType", adapterType),
				new NameValuePair("adapterGroupNm", adapterGroupName), new NameValuePair("adapterNm", adapterName),
				new NameValuePair("adapterStartStop", control) };

		// Agent를 호출한다.
		CallAgentUtil util = new CallAgentUtil();
		String message = util.getAgentDataToString(url, postParameters);
		return ResponseEntity.ok(SimpleResponse.of(message));
	}

	@RequestMapping(value = "/onl/adapter/http/httpStatus.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();
		@SuppressWarnings("unchecked")
		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;
	}

}