package com.eactive.eai.rms.onl.manage.adapter.adapterchange;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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.common.util.SystemUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
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.onl.manage.adapter.adapter.AdapterManService;
import com.eactive.eai.rms.onl.manage.comm.server.ServerManService;

/**
 * <pre>
 *     1. 기능 : 어뎁터 관리 화면의 컨트롤러
 * </pre>
 * @author : music75
 * 
 * 2022. 02. 04.
 * @author : sunwook
 * 
 * 개발에서 adapterChangeMan.jsp 화면으로 조작 하여
 * 테스트 AdapterChangeCommandController가 요청을 받아서 ON/OFF 처리 
 * 
 */
@SuppressWarnings("unchecked")
@Controller
public class AdapterChangeController extends BaseController {
	
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@Autowired
	@Qualifier("adapterChangeService")
	private AdapterChangeService service;	
	
	@Autowired
	private AdapterManService adapterManService;	
	
	@Autowired
	private ServerManService serverManService;
    
	@RequestMapping(value= "/onl/admin/adapter/adapterChangeMan.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/admin/adapter/adapterChangeMan.json",params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, JsonPageVo pageVo, @RequestParam HashMap<String,Object> paramMap) throws Exception {
    	
		Map returnMap = new HashMap();
		
		/** dev_adapterList **/
		List<HashMap<String, Object>> dev_adapterList = service.selectChgAdapterList(paramMap);
		
		try {
			
			/** test_adapterList **/
			List<HashMap<String, Object>> test_adapterList = service.getTest_adapterList(paramMap);
			
			/** useYn mapping **/
			for(HashMap<String, Object> dev_adapter : dev_adapterList) {
				
				String dev_groupName = (String) dev_adapter.get("ADPTRBZWKGROUPNAME");
				
				for(HashMap<String, Object> test_adapter : test_adapterList) {
					
					String test_groupName = (String) test_adapter.get("ADPTRBZWKGROUPNAME");
					
					if(dev_groupName.equals(test_groupName)) {
						dev_adapter.put("ADPTRUSEYN2", test_adapter.get("ADPTRUSEYN"));
						break;
					}
				}
				
			}
			
		} catch (Exception e) {
			
			logger.error(e.getMessage());
			returnMap.put("errMsg", "TEST 어댑터 정보 호출 중 에러 : " + e.getMessage());
			throw e;
		}
		
		/** sort by adapterName **/
		final Comparator<HashMap<String, Object>> adapterName_comparator = (map1, map2) -> ((String)map1.get("ADPTRBZWKGROUPNAME")).compareTo((String)map2.get("ADPTRBZWKGROUPNAME"));
		
		List<HashMap<String, Object>> sortedBy_adapterName = dev_adapterList.stream().sorted(adapterName_comparator).collect(Collectors.toList());
		
		/** remove SOCKET adapter **/
		List<HashMap<String, Object>> remove_socketAdapter = sortedBy_adapterName.stream().filter(map -> !((String) map.get("ADPTRBZWKGROUPNAME")).contains("SOCKET")).collect(Collectors.toList());
		
		returnMap.put("rows", remove_socketAdapter);
		ModelAndView modelAndView = new ModelAndView("jsonView", returnMap);
		
		return modelAndView;
	}
    
    @RequestMapping(value= "/onl/admin/adapter/adapterChangeMan.json",params = "cmd=UPDATE_STARTSTOP")
    public ModelAndView updateChangeAdapter( HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, String> paramMap) throws Exception {

    	String serviceType = paramMap.get("serviceType").toString();
    	
    	/** 개발 서버에서만 OPERATION **/
    	if(!SystemUtil.isDevServer()) {
    		throw new Exception("개발서버에서만 변경 가능합니다.");
    	}
    	
    	/** 대외 어댑터만 OPERATION **/
    	if(!serviceType.equals(DataSourceTypeManager.FEP)) {
    		throw new Exception("대외 MCI에서만 가능합니다.");
    	}
    	
    	String message = service.adapterStartStop(paramMap);
    	
    	service.insertAdapterUserInfo(paramMap);

    	HashMap resultMap = new HashMap();
		resultMap.put("message", message);
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;            
    }
    
	@RequestMapping(value= "/onl/admin/adapter/adapterChangeMan.json",params = "cmd=LIST_SELECT_ADAPTER")
  	private ModelAndView selectAdapterStatus(HttpServletRequest request, JsonPageVo pageVo, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		String serviceType = (String) paramMap.get("serviceType");
		
		if(!SystemUtil.isDevServer()) {
			throw new Exception("개발서버에서만 조회 가능합니다.");
		}
		
		if(!serviceType.equals(DataSourceTypeManager.FEP)) {
			throw new Exception("대외MCI에서만 조회 가능합니다.");
		}
		
		DataSourceType datasource = DataSourceTypeManager.getDataSourceType(serviceType);
		DataSourceContextHolder.setDataSourceType(datasource);
		
  		List<HashMap<String, Object>> dev_list = service.getLocalStatusList(paramMap, "DEV");
  		List<HashMap<String, Object>> test_list = service.getTestStatusList(paramMap);
  		
		List<HashMap<String, Object>> resultRows = new ArrayList<HashMap<String,Object>>();
		
		resultRows.addAll(dev_list);
		resultRows.addAll(test_list);
  		
  		Map resultMap = new HashMap();
  		resultMap.put("rows", resultRows);
  		
  		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
  		return modelAndView;
	}   
    
    @RequestMapping(value= "/onl/admin/adapter/adapterChangeMan.json",params = "cmd=LIST_USER_INFO")
	private ModelAndView selectListStatus(HttpServletRequest request, @RequestParam HashMap<String,Object> paramMap) throws Exception {
			   	
		Map resultMap = new HashMap();

		resultMap.put("rows", service.selectChgAdapterUserInfo(paramMap));
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);		
		return modelAndView;       
    }
    
}
