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

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.eaimsg.EAIMessageUISearch;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;
import com.eactive.eai.rms.onl.transaction.simpleinterface.ui.SimpleInterfaceUI;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class SimpleInterfaceController extends OnlBaseAnnotationController {

    public static final Log logger = LogFactory.getLog(SimpleInterfaceController.class);    

    @Autowired
    public SimpleInterfaceService service;

	@GetMapping(value = "/onl/transaction/simpleinterface/simpleInterfaceMan.view")
	public void view() {
	}

	@GetMapping(value = "/onl/transaction/simpleinterface/simpleInterfaceMan.view", params = "cmd=DETAIL")
	public String viewDetail() {
		return "/onl/transaction/simpleinterface/simpleInterfaceManDetail";
	}

	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<SimpleInterfaceUI>> selectList(EAIMessageUISearch eaiMessageUISearch,
																	  Pageable pageable, String sortname,  String sortorder) {
		Page<SimpleInterfaceUI> page = service.selectList(eaiMessageUISearch, pageable, sortname, sortorder);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=DETAIL")
	public ResponseEntity<SimpleInterfaceUI> selectDetail(String eaiSvcName) throws Exception {
		SimpleInterfaceUI simpleInterfaceUI = service.selectDetail(eaiSvcName);
		return ResponseEntity.ok(simpleInterfaceUI);
	}
	
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=LIST_COMBO")
	public ResponseEntity<Map<String, Object>> selectCombo(HttpServletRequest request) throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, Object> map = service.selectCombo(userId);
		return ResponseEntity.ok(map);
	}
	
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=LIST_DETAIL_COMBO")
	public ResponseEntity<Map<String, Object>> selectDetailCombo(HttpServletRequest request) throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, Object> map = service.selectDetailCombo(userId);
		return ResponseEntity.ok(map);
	}		
	
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=DETAIL_ADAPTER_URL")
	public ResponseEntity<Map<String, Object>> getHttpAdapterUrl(String adapterGroupName) throws Exception {
		Map<String, Object> map = service.getAdapterUrl(adapterGroupName);
		return ResponseEntity.ok(map);
	}
	
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=DETAIL_ADAPTER_GROUP")
	public ResponseEntity<AdapterGroupUI> selectAdapterGroupDetail(String adapterGroupName) throws Exception {
		return ResponseEntity.ok(service.selectAdapterGroupDetail(adapterGroupName));
	}

	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=INSERT")
	public ResponseEntity<Map<String, Object>> insert(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		try {
			List<String> standardMessageKeyList = service.insert(simpleInterfaceUI);
			Map<String, Object> resultMap = null;
			for (String standardMessageKey : standardMessageKeyList){
				resultMap = reloadSync(standardMessageKey, simpleInterfaceUI);
			}
			return ResponseEntity.ok(resultMap);
		}catch(Exception e) {
			logger.error(e);
			if(e instanceof BizException) {
				throw e;
			}
			throw new BizException("오류가 발생했습니다. 확인바랍니다. error:"+e.getMessage(), e);
		}
	}
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json", params = "cmd=UPDATE")
	public ResponseEntity<Map<String, Object>> update(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		try {
			List<String> standardMessageKeyList = service.update(simpleInterfaceUI);
			Map<String, Object> resultMap = null;
			for (String standardMessageKey : standardMessageKeyList){
				 resultMap = reloadSync(standardMessageKey, simpleInterfaceUI);	
			}
			return ResponseEntity.ok(resultMap);
		}catch(Exception e) {
			if(e instanceof BizException) {
				throw e;
			}
			if(e instanceof DuplicateKeyException) {
				DuplicateKeyException dupEx = (DuplicateKeyException) e;
				Throwable cause = dupEx.getMostSpecificCause();
				throw new BizException("중복 오류가 발생했습니다. 확인바랍니다. 오류메시지: "+cause.getMessage());
			}
			logger.error(e);
			throw new BizException("오류가 발생했습니다. 확인바랍니다. 오류메시지: "+e.getMessage());
		}

	}
	@PostMapping(value= "/onl/transaction/simpleinterface/simpleInterfaceMan.json",params = "cmd=DELETE")
	public ResponseEntity<Map<String, Object>> delete(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		try {
			String standardMessageKey = service.delete(simpleInterfaceUI);
			Map<String, Object> resultMap = deleteSync(standardMessageKey, simpleInterfaceUI);
			return ResponseEntity.ok(resultMap);
		}catch(Exception e) {
			if(e instanceof BizException) {
				throw e;
			}
			throw new BizException("오류가 발생했습니다. 확인바랍니다. error:"+e.getMessage(), e);
		}
	}

	public Map<String, Object> reloadSync(String standardMessageKey, SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		logger.info("- 수정 동기화 시작 [" + simpleInterfaceUI.getEaiSvcName() + "]");

		//HS04,HS05 내부표준전문
		if (StringUtils.isNotBlank(standardMessageKey)){
			//URL 변경 시 KEY 자체가 변경되므로 이전 가비지가 남게됨 우선 ALL로 처리
			Command command = new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand", "ALL");
			agentUtilService.broadcast(command);
		}

		//HE01 EAI 메시지 공통부
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand", simpleInterfaceUI.getEaiSvcName());
		HashMap<String, Object> resultMap = agentUtilService.broadcast(cmdHE01);
		logger.info("- 수정 동기화 완료 [" + simpleInterfaceUI.getEaiSvcName() + "]");
		return resultMap;
	}

	public Map<String, Object> deleteSync(String standardMessageKey, SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		logger.info("- 삭제 동기화 시작 [" + simpleInterfaceUI.getEaiSvcName() + "]");
		//HS04,HS05 내부표준전문
		callCommandIfExists(standardMessageKey, "com.eactive.eai.agent.stdmessage.RemoveSTDMessageCommand");

		//HE01 EAI 메시지 공통부
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.RemoveEAIMessageCommand", simpleInterfaceUI.getEaiSvcName());
		HashMap<String, Object> resultMap = agentUtilService.broadcast(cmdHE01);

		// Transform 및 Layout 삭제
		callCommandIfExists(simpleInterfaceUI.getRequestTransform(), "com.eactive.eai.agent.transformer.RemoveTransformCommand");
		callCommandIfExists(simpleInterfaceUI.getResponseTransform(), "com.eactive.eai.agent.transformer.RemoveTransformCommand");
		callCommandIfExists(simpleInterfaceUI.getInboundRequestLayout(), "com.eactive.eai.agent.transformer.RemoveLayoutCommand");
		callCommandIfExists(simpleInterfaceUI.getOutboundRequestLayout(), "com.eactive.eai.agent.transformer.RemoveLayoutCommand");
		callCommandIfExists(simpleInterfaceUI.getInboundResponseLayout(), "com.eactive.eai.agent.transformer.RemoveLayoutCommand");
		callCommandIfExists(simpleInterfaceUI.getOutboundResponseLayout(), "com.eactive.eai.agent.transformer.RemoveLayoutCommand");

		logger.info("- 삭제 동기화 완료 [" + simpleInterfaceUI.getEaiSvcName() + "]");
		return resultMap;
	}

	public void callCommandIfExists(String value, String commandName) throws Exception {
		if (StringUtils.isNotBlank(value)) {
			agentUtilService.broadcast(new CommonCommand(commandName, value));
		}
	}
}
