package com.eactive.eai.rms.common.mmilog;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.base.BaseAnnotationController;
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.eactive.eai.rms.data.entity.onl.mmilog.MMILogSearch;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class MMILogController extends BaseAnnotationController {

	private MMILogManService mmiLogManService;

	private ComboService comboService;

	private ObjectMapper objectMapper;

	@Autowired
	public MMILogController(MMILogManService mmiLogManService, ComboService comboService, ObjectMapper objectMapper) {
		this.mmiLogManService = mmiLogManService;
		this.comboService = comboService;
		this.objectMapper = objectMapper;
	}

	@GetMapping(value = "/common/acl/mmiLog/mmiLogMan.view")
	public void view() {
		// view
	}

	@GetMapping(value = "/common/acl/mmiLog/mmiLogMan.view", params = "cmd=DETAIL")
	public String viewList() {
		return "/common/acl/mmiLog/mmiLogManDetail";
	}

	@PostMapping(value = "/common/acl/mmiLog/mmiLogMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<MMILogUI>> selectList(@SortDefault(sort = "id.msgDpstHms", direction = Direction.DESC) Pageable pageable, MMILogSearch mmiLogSearch) {
		Page<MMILogUI> page = mmiLogManService.selectList(pageable, mmiLogSearch);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value = "/common/acl/mmiLog/mmiLogMan.json", params = "cmd=LIST_INIT_COMBO")
	public ResponseEntity<Map<String, Object>> eaiSvcNameCombo() {
		List<ComboVo> listInoutTypeCd = comboService.getFromCode("INOUT_TYPE");

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("inoutTypeRows", listInoutTypeCd);
		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/common/acl/mmiLog/mmiLogMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(MMILogSearch mmiLogSearch, @RequestParam Map<String, Object> paramMap)
			throws JsonProcessingException {

		Map<String, Object>[] datas = mmiLogManService.selectListToExcel(mmiLogSearch);

		String[] headers = objectMapper.readValue((String) paramMap.get("header"), String[].class);
		String[] headerTitles = objectMapper.readValue((String) paramMap.get("headerTitle"), String[].class);

		HashMap<String, Object>[] lmerge = null;
		String merge = (String) paramMap.get("merge");

		if (merge != null) {
			lmerge = objectMapper.readValue(merge, new TypeReference<HashMap<String, Object>[]>() {
			});
		}

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", datas);
		resultMap.put("fileName", paramMap.get("fileName"));
		resultMap.put("merge", lmerge);
		return new ModelAndView("excelView", resultMap);
	}

	@PostMapping(value = "/common/acl/mmiLog/mmiLogMan.json", params = "cmd=DETAIL")
	public ResponseEntity<MMILogUI> selectDetail(MMILogUI mmiLogUI) {
		MMILogUI ui = mmiLogManService.selectDetail(mmiLogUI);
		return ResponseEntity.ok(ui);
	}
	
	@GetMapping(value = "/common/acl/mmiLog/mmiLogMan.json", params = "cmd=DETAIL_XML")
	public String showXML(HttpServletRequest request, MMILogUI mmiLogUI, String key, String type) {
		String message = "데이터 조회 실패";
		MMILogUI data = mmiLogManService.selectDetail(mmiLogUI);

		if (data != null) {
			String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
			String xmlData = data.getReqDstcd();
			String[] sptXmlData = StringUtils.splitByWholeSeparatorPreserveAllTokens(xmlData, header);
			
			Optional<String> matchedSegment = Arrays.stream(sptXmlData)
					.filter(segment ->  segment != null && 
											(segment.contains("sysSvcName=\"" + key) && "eaiSvcName".equals(type) || 
											 segment.contains("layoutId=\"" + key) || 
											 segment.contains("id=\"" + key)))
					.findFirst();
			
			if(matchedSegment.isPresent()) {
				message = header + (matchedSegment.get()).replaceAll("[\\r\\n\\t]", "");
			}
		}
		//data == null
		request.setAttribute("param", message);
		return  "forward:/common/jsp/popupXmlBrowser.jsp";
	}

}
