package com.eactive.eai.rms.onl.manage.inflow.group;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
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;

@Controller
public class InflowGroupControlManController extends OnlBaseAnnotationController {

	@Autowired
	private InflowGroupControlManService service;

	@Autowired
	private ComboService comboService;

	private ObjectMapper objectMapper = new ObjectMapper();

	// ========== View Mappings ==========

	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.view")
	public String viewList() {
		return "/onl/admin/inflow/inflowGroupControlMan";
	}

	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.view", params = "cmd=DETAIL")
	public String viewDetail() {
		return "/onl/admin/inflow/inflowGroupControlManDetail";
	}

	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.view", params = "cmd=INTERFACE_POPUP")
	public String viewInterfacePopup() {
		return "/onl/admin/inflow/inflowGroupInterfacePopup";
	}

	// ========== JSON API Mappings ==========

	/**
	 * 그룹 목록 조회
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<InflowGroupControlManUI>> selectList(HttpServletRequest request,
			Pageable pageVo, String searchGroupName, String searchUseYn) {
		Page<InflowGroupControlManUI> uiPage = service.selectGroupList(pageVo, searchGroupName, searchUseYn);
		return ResponseEntity.ok(new GridResponse<>(uiPage));
	}

	/**
	 * 그룹 상세 조회
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=DETAIL")
	public ResponseEntity<InflowGroupControlManUI> selectDetail(HttpServletRequest request,
			HttpServletResponse response, String groupId) {
		InflowGroupControlManUI ui = service.selectGroupDetail(groupId);
		return ResponseEntity.ok(ui);
	}

	/**
	 * 그룹 저장 (INSERT)
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=INSERT")
	public ResponseEntity<Void> insert(HttpServletRequest request, HttpServletResponse response, InflowGroupControlManUI ui,
			@RequestParam(value = "interfaceListJson", required = false) String interfaceListJson) throws Exception {
		parseInterfaceList(ui, interfaceListJson);
		String modifiedBy = getSessionUserId(request);
		service.mergeGroup(ui, modifiedBy);

		// Agent Command 전송
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.inflow.ReloadInflowGroupControlCommand",
				ui.getGroupId());
		agentUtilService.broadcast(command);
		return ResponseEntity.ok().build();
	}

	/**
	 * 그룹 저장 (UPDATE)
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=UPDATE")
	public ResponseEntity<Void> update(HttpServletRequest request, HttpServletResponse response, InflowGroupControlManUI ui,
			@RequestParam(value = "interfaceListJson", required = false) String interfaceListJson) throws Exception {
		parseInterfaceList(ui, interfaceListJson);
		String modifiedBy = getSessionUserId(request);
		service.mergeGroup(ui, modifiedBy);

		// Agent Command 전송
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.inflow.ReloadInflowGroupControlCommand",
				ui.getGroupId());
		agentUtilService.broadcast(command);
		return ResponseEntity.ok().build();
	}

	/**
	 * 그룹 삭제
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=DELETE")
	public ResponseEntity<Void> delete(HttpServletRequest request, HttpServletResponse response, String groupId) throws Exception {
		service.deleteGroup(groupId);

		// Agent Command 전송
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.inflow.RemoveInflowGroupControlCommand",
				groupId);
		agentUtilService.broadcast(command);
		return ResponseEntity.ok().build();
	}

	/**
	 * 콤보박스 초기화 데이터
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) {
		List<ComboVo> useYnRows = comboService.getFromCode("USE_YN");
		List<ComboVo> timeUnitRows = comboService.getFromCode("INFLOW_CTRL_TIME_UNIT");

		Map<String, List<ComboVo>> resultMap = new HashMap<>();
		resultMap.put("useYnRows", useYnRows);
		resultMap.put("timeUnitRows", timeUnitRows);

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

	/**
	 * 인터페이스 목록 조회 (팝업용)
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=INTERFACE_LIST")
	public ResponseEntity<GridResponse<InflowGroupMappingUI>> selectInterfaceList(HttpServletRequest request,
			Pageable pageVo, String searchName) {
		Page<InflowGroupMappingUI> uiPage = service.selectInterfaceListForPopup(pageVo, searchName);
		return ResponseEntity.ok(new GridResponse<>(uiPage));
	}

	/**
	 * 인터페이스 중복 등록 체크
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=LIST_CHECK_DUPLICATE")
	public ModelAndView checkDuplicate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("interfaceId") String interfaceId,
			@RequestParam(value = "groupId", required = false) String groupId) {
		String existingGroupName = service.checkInterfaceDuplicate(interfaceId, groupId);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("duplicate", existingGroupName != null);
		resultMap.put("groupName", existingGroupName);

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

	/**
	 * 그룹 버킷 상태 조회 (GW 서버별 현황)
	 */
	@RequestMapping(value = "/onl/admin/inflow/inflowGroupControlMan.json", params = "cmd=LIST_BUCKET_STATUS")
	public ModelAndView getBucketStatus(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("groupId") String groupId) {
		List<Map<String, Object>> statusList = service.getGroupBucketStatus(groupId);

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

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

	/**
	 * JSON 문자열을 인터페이스 목록으로 변환
	 */
	private void parseInterfaceList(InflowGroupControlManUI ui, String interfaceListJson) throws Exception {
		if (interfaceListJson != null && !interfaceListJson.isEmpty()) {
			List<InflowGroupMappingUI> interfaceList = objectMapper.readValue(interfaceListJson,
					new TypeReference<List<InflowGroupMappingUI>>() {
					});
			ui.setInterfaceList(interfaceList);
		}
	}

	/**
	 * 세션에서 사용자 ID 조회
	 */
	private String getSessionUserId(HttpServletRequest request) {
		Object userId = request.getSession().getAttribute("userId");
		return userId != null ? userId.toString() : "SYSTEM";
	}
}
