package com.eactive.eai.rms.onl.transaction.extnl;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.SortDefault;
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.agent.command.CommonCommand;
import com.eactive.eai.data.entity.onl.unifbwk.UnifBwkTp;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
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.data.entity.onl.eaimsg.EAIMessageUISearch;
import com.eactive.eai.rms.data.entity.onl.unifbwk.UnifBwkTpService;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;
import com.eactive.eai.rms.onl.transaction.extnl.ui.InterfaceUI;

@Controller
public class InterfaceManController extends BaseController {

    private static final Logger logger = Logger.getLogger(InterfaceManController.class);    

	@Autowired
	@Qualifier("interfaceManService")
	private InterfaceManService interfaceManService;

	@Autowired
	private ComboService comboService;

	@Autowired
	private UnifBwkTpService unifBwkTpService;
    
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.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/transaction/extnl/interfaceMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<InterfaceUI>> selectList(EAIMessageUISearch eaiMessageUISearch,
			Pageable pageable, String sortname,  String sortorder) {
		Page<InterfaceUI> page = interfaceManService.selectList(eaiMessageUISearch, pageable, sortname, sortorder);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=DETAIL")
	private ResponseEntity<InterfaceUI> selectDetail(String eaiSvcName) {
		InterfaceUI interfaceUI = interfaceManService.selectDetail(eaiSvcName);
		return ResponseEntity.ok(interfaceUI);
	}
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=INSERT")
	private String insert(InterfaceUI interfaceUI) throws Exception {

		interfaceManService.insert(interfaceUI);
		reloadSync(interfaceUI);
		return null;
	}	
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=UPDATE")
	private String update(InterfaceUI interfaceUI) throws Exception {

		interfaceManService.update(interfaceUI);
		reloadSync(interfaceUI);
		return null;
	}
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=DELETE")
	private String delete(InterfaceUI interfaceUI) throws Exception {
		interfaceManService.delete(interfaceUI);
		deleteSync(interfaceUI);
		return null;
	}
	
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=LIST_COMBO")
	public ResponseEntity<Map<String, Object>> selectCombo() throws Exception {

		List<ComboVo> listBiz = comboService.getFromBusinessType();
		Map<String, Object> resultMap = new HashMap<>();

		resultMap.put("bizList", listBiz);

		return ResponseEntity.ok(resultMap);
	}	
	
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=LIST_DETAIL_COMBO")
	public ResponseEntity<Map<String, Object>> selectDetailCombo() throws Exception {

		List<ComboVo> listBiz = comboService.getFromBusinessType();
		List<ComboVo> listIo = comboService.getFromCode("IO_TYPE"); // 내부외부구분
		List<ComboVo> listReqResList = comboService.getFromCode("REQRES_TYPE"); // 전문요청구분
		List<ComboVo> listSyncAsyncList = comboService.getFromCode("SYNCASYNC_TYPE"); // 송수신방법
		Iterable<UnifBwkTp> unifBwkTpIterable = unifBwkTpService.findByInputdstcd("EXT");

		Map<String, Object> resultMap = new HashMap<>();

		resultMap.put("bizList", listBiz);
		resultMap.put("ioList", listIo);
		resultMap.put("reqResList", listReqResList);
		resultMap.put("syncAsyncList", listSyncAsyncList);
		resultMap.put("extBizList", unifBwkTpIterable);

		return ResponseEntity.ok(resultMap);
	}		
	@RequestMapping(value= "/onl/transaction/extnl/interfaceMan.json",params = "cmd=LIST_ADAPTER_COMBO")
	public ResponseEntity<Map<String, Object>> selectAdapterCombo(String adptrCd, String adptrIoDstcd) {

		List<AdapterGroupUI> resultList = interfaceManService.selectAdapterCombo(adptrIoDstcd);

		Map<String, Object> resultMap = new HashMap<>();

		resultMap.put("adapter", resultList);

		return ResponseEntity.ok(resultMap);
	}

	@RequestMapping(value = "/onl/transaction/extnl/interfaceMan.json", params = "cmd=INITIALIZE_EAITRANNAME")
	public ModelAndView generateInterfaceId(@RequestParam HashMap<String, String> paramMap) throws Exception {

		String intfId = interfaceManService.getIncresedInterfaceId(paramMap);

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

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

		return modelAndView;
	}
		
	public void reloadSync(InterfaceUI interfaceUI) throws Exception {
		logger.debug("--------------------------------------------------------------------------");
		logger.info("- 동기화 처리 -------------------------------------------------------------");
		StringBuffer result = new StringBuffer();

		// 기존 정보 조회 및 확인
		logger.debug("eaiSvcName : [" + interfaceUI.getEaiSvcName() + "]");

		result.append("-[내부표준메세지 초기화]-------------------");
		// HS04,HS05 내부표준전문
		String key = interfaceUI.getBzwkSvcKeyName();
		if (key != null && !"".equals(key)) {
			CommonCommand cmdHS = new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand", key);
			agentUtilService.broadcast(cmdHS);
		}
		result.append("---------------------------------------");

		result.append("-[IF메세지 초기화]------------------------");
		// HE01 EAI 메시지 공통부
		key = interfaceUI.getEaiSvcName();
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand", key);
		;
		agentUtilService.broadcast(cmdHE01);
		result.append("---------------------------------------");

		result.append("-[필드추출정보 초기화]---------------------");
		// 메모리 정보 Reload
		key = interfaceUI.getEaiSvcName();
		CommonCommand cmdFR03 = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand", key);
		;
		agentUtilService.broadcast(cmdFR03);
		logger.debug("--------------------------------------------------------------------------");
		logger.info(result.toString());
	}

	public void deleteSync(InterfaceUI interfaceUI) throws Exception {
		logger.debug("--------------------------------------------------------------------------");
		logger.info("- 동기화 처리 -------------------------------------------------------------");
		StringBuffer result = new StringBuffer();

		// 기존 정보 조회 및 확인
		logger.debug("eaiSvcName : [" + interfaceUI.getEaiSvcName() + "]");

		result.append("-[내부표준메세지 초기화]-------------------");
		// HS04,HS05 내부표준전문
		String key = interfaceUI.getBzwkSvcKeyName();
		if (key != null && !"".equals(key)) {
			CommonCommand cmdHS = new CommonCommand("com.eactive.eai.agent.stdmessage.RemoveSTDMessageCommand", key);
			agentUtilService.broadcast(cmdHS);
		}
		result.append("---------------------------------------");

		result.append("-[IF메세지 초기화]------------------------");
		// HE01 EAI 메시지 공통부
		key = interfaceUI.getEaiSvcName();
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.RemoveEAIMessageCommand", key);
		;
		agentUtilService.broadcast(cmdHE01);
		result.append("---------------------------------------");

		result.append("-[필드추출정보 초기화]---------------------");
		// 메모리 정보 Reload
		key = interfaceUI.getEaiSvcName();
		CommonCommand cmdFR03 = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand", key);
		;
		agentUtilService.broadcast(cmdFR03);
		logger.debug("--------------------------------------------------------------------------");
		logger.info(result.toString());
	}	
	
	@PostMapping(value = "/onl/transaction/extnl/interfaceMan.json", params = "cmd=LIST_POP")
	public ResponseEntity<GridResponse<InterfaceUI>> selectPopList(@SortDefault("eaisvcname") Pageable pageable, String eaiSvcName) {
		
		String serviceType = DataSourceContextHolder.getDataSourceType().getName();
		Page<InterfaceUI> page = interfaceManService.selectPopList(pageable, eaiSvcName, serviceType);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

}
