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

import java.net.URLEncoder;
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.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.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.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
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.vo.HostInfomationForm;

@Controller
public class SocketErrorContentsController extends BaseController {

	private final String AGENT_PAGE = "adapter_log_agent.jsp";

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

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

	@Autowired
	private EAIServerService eaiServerService;

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

		// 업무구분
		List<ComboVo> instanceList = comboService.getFromEAIServerWithoutAll();

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

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

	@RequestMapping(value = "/onl/adapter/socket/socketErrorContents.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, JsonPageVo pageVo, String searchEaiSevrInstncName,
			String searchText) throws Exception {

		EAIServer selectedServer = eaiServerService.getByEaiSevrInstncName(searchEaiSevrInstncName);

		// LOG 파일 위치 프라퍼티로
		String defaultLogPath = monitoringContext.getStringProperty(MonitoringContext.DEFAULT_LOG_PATH, "/fslog/eai/");
		String socketErrorLogFile = monitoringContext
				.getStringProperty(MonitoringContext.SOCKET_ERROR_LOG_FILE, "netAdapterError.log");
		String logPath = "";

		if (defaultLogPath == null || defaultLogPath.equals("")) {
			logPath = "/fslog/eai/" + searchEaiSevrInstncName + socketErrorLogFile;
		} else {
			logPath = defaultLogPath + searchEaiSevrInstncName + "/" + socketErrorLogFile;
		}

		// http://192.168.68.21:30311/ONLWeb/agent/host/adapter_log_agent.jsp?fileName=/fslog/eai/EAIDS01_i01/netAdapter.log
		// searchText=[찾으려는값]
		// checkHead=[라인의 시작문자]
		// skipLineCount=[이전페이지의 마지막 라인수]
		String url = "http://" + selectedServer.getEaisevrip() + ":" + selectedServer.getSevrlsnportname()
				+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH + AGENT_PAGE + "?fileName=" + logPath + "&searchText="
				+ URLEncoder.encode(searchText);

		logger.info("url : " + url);

		CallAgentUtil util = new CallAgentUtil();
		List<HashMap<String, Object>> list = new ArrayList<>();
		HashMap map = null;
		String result = util.getAgentDataToString(url);

		int linePoint = 0;

		// 정보를 라인단위로 파싱하여
		if (result != null) {
			linePoint = result.indexOf("\n");
		}

		while (linePoint > -1) {
			map = new HashMap();
			// 한 라인만을 읽어 온다.
			String line = null;
			if (result != null) {
				line = result.substring(0, linePoint);
			}

			if (result != null) {
				result = result.substring(linePoint + 1);
			}
			map.put("logContent", line);
			list.add(map);

			linePoint = result.indexOf("\n");
		}

		Map resultMap = new HashMap();
		resultMap.put("total", pageVo.getTotal()); // 전체 페이지수
		resultMap.put("page", pageVo.getPage()); // 현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());// 전체 레코드건수
		resultMap.put("rows", list);

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

	}

}
