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.apache.commons.lang3.StringUtils;
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.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
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.common.vo.GridResponse;
import com.eactive.eai.rms.common.vo.SimpleResponse;
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.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;
import com.google.gson.Gson;

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

	private ComboService comboService;

	private AdapterManService adapterManService;

	private EAIServerService eaiServerService;

	@Autowired
	protected SocketConnectionController(ComboService comboService, AdapterManService adapterManService,
			EAIServerService eaiServerService) {
		this.comboService = comboService;
		this.adapterManService = adapterManService;
		this.eaiServerService = eaiServerService;
	}

	@RequestMapping(value = "/onl/adapter/socket/socketConnection.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;
	}

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

		List<EAIServer> serverList = new ArrayList<>();
		if (StringUtils.isEmpty(searchEaiSevrInstncName)) {
			serverList.addAll(eaiServerService.selectEaiServerIpList());
		} else {
			serverList.add(eaiServerService.getByEaiSevrInstncName(searchEaiSevrInstncName));
		}

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

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

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

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

	@PostMapping(value = "/onl/adapter/socket/socketConnection.json", params = "cmd=TRANSACTION_STARTSTOP")
	public ResponseEntity<SimpleResponse> transactionStartStop(HttpServletRequest request,
			String searchEaiSevrInstncName, String adptrBzwkGroupName, String adptrBzwkName, String remoteAddress,
			String localAddress, String session) throws Exception {

		EAIServer eaiServer = eaiServerService.getByEaiSevrInstncName(searchEaiSevrInstncName);

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

		// cmd 는 start/stop
		NameValuePair[] postParameters = new NameValuePair[] {
				new NameValuePair("adapterGroupName", adptrBzwkGroupName),
				new NameValuePair("adapterName", adptrBzwkName), new NameValuePair("remoteAddress", remoteAddress),
				new NameValuePair("localAddress", localAddress), new NameValuePair("sessionName", session) };

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

		return ResponseEntity.ok(SimpleResponse.of(message));
	}

	@RequestMapping(value = "/onl/adapter/socket/socketConnection.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) {

		// 업무구분
		List<ComboVo> instanceList = comboService.getFromEAIServerWithoutAll();
		List<AdapterGroupUI> adapterList = adapterManService.selectSocketAdapterGroup("NET");

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("instanceList", instanceList);
		resultMap.put("adapterList", adapterList);

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

	@RequestMapping(value = "/onl/adapter/socket/socketConnection.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;
	}

}
