package com.eactive.eai.rms.common.acl.user.util;

import com.eactive.eai.rms.common.acl.user.ui.AdminLoginVo;
import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.IpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
public class UserRegistUtilController extends BaseAnnotationController {

	@Autowired
	private UserRegistUtilService userRegistUtilService;

   private final ObjectMapper mapper = new ObjectMapper();

	@GetMapping(value = "/common/acl/user/userRegistUtil.view")
	public String viewList() {
		return "/common/acl/user/userRegistUtil";
	}

	@PostMapping(value = "/common/acl/user/userRegistUtil.json", params = "cmd=DATASOURCE")
	public ResponseEntity<Map<String, Object>> selectCombo() throws Exception {

		List<DataSourceType> listDataSource = DataSourceTypeManager.getDynamicDataSourceTypes();
		Map<String, Object> resultMap = new HashMap<>();
		List<Map<String, String>> datasourceList = new ArrayList<Map<String, String>>();

		listDataSource.stream().forEach(dataSource -> {
			Map<String, String> insMap = new HashMap<>();
			insMap.put("DATASOURCE", dataSource.getName());
			datasourceList.add(insMap);
		});

		resultMap.put("dataSourceList", datasourceList);

		return ResponseEntity.ok(resultMap);
	}

	@RequestMapping(value = "/common/acl/user/userRegistUtil.json", params = "cmd=INSERT")
   public ModelAndView regist(HttpServletRequest request, @RequestParam("userList") String userList) throws Exception {

      HashMap<String, String>[] userMapList = mapper.readValue(userList, HashMap[].class);

      List<UserRegistResponseVo> responseMessageList = userRegistUtilService.registUser(userMapList, getAdminLoginVo(request));

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

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

	private AdminLoginVo getAdminLoginVo(HttpServletRequest request) {
		AdminLoginVo adminLoginVo = new AdminLoginVo();
		adminLoginVo.setLoginIp(IpUtil.getClientIp(request));
		adminLoginVo.setLoginId(SessionManager.getUserId(request));

		return adminLoginVo;
	}
}