package nlib.cmm;

import java.lang.reflect.Method;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import nlib.cmm.exception.ErrorMessage;
import nlib.cmm.service.NlibProperty;
import nlib.restful.service.DataApiResVO;
import nlib.security.SecUserVO;
import nlib.user.service.LoginService;
import nlib.user.service.NlibLoginVO;
import nlib.util.StringUtil;

/**
 * <pre>
 * @Class Name : NlibCommonController.java
 * 
 * @Description : 컨트롤러의 공통적인 기능을 제공하는 컨트롤러 상위 클래스
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 7. 23.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 7. 23.
 * @version 1.0
 *
 */
public class NlibCommonController {
	
	private static final Logger log = LoggerFactory.getLogger(NlibCommonController.class);
	
	@Resource(name = "loginService")
	private LoginService _loginService;
	
	private static final int INFO_ID_COUNCIL_CD = 1; /* 현재 지방문화원 코드를 지칭하는 식별자 */
	private static final int INFO_ID_COUNCIL_NM = 2; /* 현재 지방문화원 명칭을 지칭하는 식별자 */

	/**
	 * 스프링 시큐리티 Authentication를 통해서 사용자로그인정보 NlibLoginVO를 리턴한다.
	 *  
	 * @param authentication
	 * @return
	 */
	public NlibLoginVO getNlibLoginVO(Authentication authentication) {
		if(authentication == null) return new NlibLoginVO();
		
		return (NlibLoginVO)authentication.getPrincipal();
	}
	
	public NlibLoginVO getNlibLoginVO(HttpServletRequest request) {

		Authentication auth = (Authentication)request.getUserPrincipal();
		if(auth == null || !auth.isAuthenticated()) return new NlibLoginVO();
		
		NlibLoginVO loginVO = (NlibLoginVO)auth.getPrincipal();
		if(loginVO == null || StringUtil.isEmpty(loginVO.getMbInfoId())) return new NlibLoginVO();
		
		return loginVO;
	}
	

	/**
	 * 인증에 저장된 사용자 로그인 정보 VO의 값을 매개변수값으로 대체하여 저장하고 돌려 준다. 
	 * 
	 * @param request
	 * @param newLoginVO
	 * @return
	 */
	public NlibLoginVO replaceNlibLoginVO(HttpServletRequest request, NlibLoginVO newLoginVO) {

		if(newLoginVO == null) return null;
		
		Authentication auth = (Authentication)request.getUserPrincipal();
		if(auth == null || !auth.isAuthenticated()) return new NlibLoginVO();
		
		NlibLoginVO loginVO = getNlibLoginVO(request);
		if(loginVO == null) return null;
		
		if(!loginVO.getMbInfoId().equals(newLoginVO.getMbInfoId())) {
			log.error("replaceNlibLoginVO > 서로 다른 사용자 정보이므로 인증 LoginVO 정보를 변경할 수 없습니다.");
			return null;
		}
		
		// 값 복사작업 
		Method[] methods = NlibLoginVO.class.getMethods();
		String mName;
		HashMap<String, Method> setterNames = new HashMap<String, Method>();
		HashMap<String, Method> getterNames = new HashMap<String, Method>();
		final String skipSetterList = "|setIp|setAlerted|setAuthorityList|"; 
		for(Method m : methods) {
			mName = m.getName();
			if(skipSetterList.contains(mName)) continue;
			
			//log.debug("NlibLoginVO : methods > " + m.getName());

			if(mName.toUpperCase().startsWith("SET")) setterNames.put(mName, m);
			else if(mName.toUpperCase().startsWith("GET")) getterNames.put(mName, m);
			else if(mName.toUpperCase().startsWith("IS")) getterNames.put(mName, m);
		}
		
		String getterName;
		for(String setterName : setterNames.keySet()) {
			getterName = "get" + setterName.substring(3);
			Method setter = setterNames.get(setterName);
			Method getter = getterNames.get(getterName);
			
			if(setter != null && getter != null) {
				try {
					String oldValue = (String)getter.invoke(loginVO);
					String newValue = (String)getter.invoke(newLoginVO);
					
					setter.invoke(loginVO, getter.invoke(newLoginVO));
					//log.debug("replaceNlibLoginVO > Method invoke : " + setterName + " : " + oldValue + " -> " + newValue);
					
				} catch(Exception e) {
					log.error("replaceNlibLoginVO > Method invoke error : " + setterName + ", " + getterName);
					e.printStackTrace();
				}
			}
			
		}
		
		return loginVO;
	}
	
	
	/**
	 * 사용자로그인정보 ID를 리턴한다.
	 * 로그인하지 않은 경우, null을 리턴한다. 
	 *  
	 * @param request
	 * @return
	 */
	public String getMbInfoId(HttpServletRequest request) {
		
		Authentication auth = (Authentication)request.getUserPrincipal();
		if(auth == null || !auth.isAuthenticated()) return null;
		
		NlibLoginVO loginVO = (NlibLoginVO)auth.getPrincipal();
		if(loginVO == null || StringUtil.isEmpty(loginVO.getMbInfoId())) return null;
		
		return loginVO.getMbInfoId();
	}
	
	/**
	 * 스프링 시큐리티 Authentication를 통해서 사용자로그인정보 SecUserVO를 리턴한다.
	 * 
	 * @param authentication
	 * @return
	 */
	public SecUserVO getSecLoginVO(Authentication authentication) {
		
		if(authentication == null) return null;
		
		return (SecUserVO)authentication.getPrincipal();
	}
	
	public ResponseEntity<String> makeResponseEntityJson(DataApiResVO resVO) {

		// Convert Json
		ObjectMapper mapper = new ObjectMapper();
		String jsonStr = null;
		
		HttpHeaders headers = new HttpHeaders();
	    headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
	    
		try {
			jsonStr = mapper.writeValueAsString(resVO);
			log.debug("RETURN DATA > json:" + jsonStr);
		} catch (JsonProcessingException e) {
			ErrorMessage eMsg = new ErrorMessage("ERR_JSON_CONVERT", "응답객체를 JSON으로 변환 처리 중 오류가 발생하였습니다. : " + e.toString());
			try { jsonStr = mapper.writeValueAsString(eMsg); } catch (JsonProcessingException ee) {}
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).headers(headers).body(jsonStr);
		}

	    return ResponseEntity.ok().headers(headers).body(jsonStr);
	}
	

	public ResponseEntity<String> makeResponseEntityJson(List<HashMap<String,String>> list) {

		// Convert Json
		ObjectMapper mapper = new ObjectMapper();
		String jsonStr = null;
		
		HttpHeaders headers = new HttpHeaders();
	    headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
	    
		try {
			jsonStr = mapper.writeValueAsString(list);
			log.debug("RETURN DATA > json:" + jsonStr);
		} catch (JsonProcessingException e) {
			ErrorMessage eMsg = new ErrorMessage("ERR_JSON_CONVERT", "응답객체를 JSON으로 변환 처리 중 오류가 발생하였습니다. : " + e.toString());
			try { jsonStr = mapper.writeValueAsString(eMsg); } catch (JsonProcessingException ee) {}
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).headers(headers).body(jsonStr);
		}

	    return ResponseEntity.ok().headers(headers).body(jsonStr);
	}

	public ResponseEntity<String> makeResponseEntityJson(HashMap<String,Object> retMap) {

		// Convert Json
		ObjectMapper mapper = new ObjectMapper();
		String jsonStr = null;
		
		HttpHeaders headers = new HttpHeaders();
	    headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
	    
		try {
			jsonStr = mapper.writeValueAsString(retMap);
			log.debug("RETURN DATA > json:" + jsonStr);
		} catch (JsonProcessingException e) {
			ErrorMessage eMsg = new ErrorMessage("ERR_JSON_CONVERT", "응답객체를 JSON으로 변환 처리 중 오류가 발생하였습니다. : " + e.toString());
			try { jsonStr = mapper.writeValueAsString(eMsg); } catch (JsonProcessingException ee) {}
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).headers(headers).body(jsonStr);
		}

	    return ResponseEntity.ok().headers(headers).body(jsonStr);
	}
	
	public ModelMap addParamsToModel(Map<String, String> paramMap, ModelMap model) {
		return addParamsToModel(paramMap, model, null, null);
	}
	public ModelMap addParamsToModel(Map<String, String> paramMap, ModelMap model, String upperMapName, String itemNames) {
		
		
		if(paramMap == null || paramMap.size() < 1) return model;
		if(model == null) return model;
		
		String filter = null;
		if(StringUtil.isNotEmpty(itemNames)) {
			filter = "," + itemNames + ",";
			filter = filter.replaceAll(" ", "");
		}
		
		boolean existUpperMap = StringUtil.isNotEmpty(upperMapName);
		Map<String, String> uppperMap = null;
		if(existUpperMap) uppperMap = new HashMap<String, String>();
		
		for(String key : paramMap.keySet()) {
			
			if(filter != null && !filter.contains("," + key + ",")) {
				continue;
			}
			if(existUpperMap) {
				uppperMap.put(key, paramMap.get(key));
			} else {
				model.addAttribute(key, paramMap.get(key));
			}
			
		}
		
		if(existUpperMap) model.addAttribute(upperMapName, uppperMap);
		
		return model;
	}
	
	
	public RedirectAttributes addParamsToRedirect(Map<String, String> paramMap, RedirectAttributes redirectAttrs) {
		return addParamsToRedirect(paramMap, redirectAttrs, null, null);
	}
	public RedirectAttributes addParamsToRedirect(Map<String, String> paramMap
			, RedirectAttributes redirectAttrs
			, String upperMapName
			, String itemNames) {
		
		
		if(paramMap == null || paramMap.size() < 1) return redirectAttrs;
		if(redirectAttrs == null) return redirectAttrs;
		
		String filter = null;
		if(StringUtil.isNotEmpty(itemNames)) {
			filter = "," + itemNames + ",";
			filter = filter.replaceAll(" ", "");
		}
		
		boolean existUpperMap = StringUtil.isNotEmpty(upperMapName);
		Map<String, String> uppperMap = null;
		if(existUpperMap) uppperMap = new HashMap<String, String>();
		
		for(String key : paramMap.keySet()) {
			
			if(filter != null && !filter.contains("," + key + ",")) {
				continue;
			}
			if(existUpperMap) {
				uppperMap.put(key, paramMap.get(key));
			} else {
				redirectAttrs.addFlashAttribute(key, paramMap.get(key));
			}
			
		}
		
		if(existUpperMap) redirectAttrs.addFlashAttribute(upperMapName, uppperMap);
		
		return redirectAttrs;
	}

	/**
	 * paramMap에 이전 요청에서 전달할 때 추가한 POST방식의 매개변수값을 paramMap에 추가한다.
	 *  
	 * @param paramMap
	 * @param req
	 */
	public void addParamFromInputFlash(Map<String, String> paramMap, HttpServletRequest req) {
		if(req == null) return;
		
		Map<String, String> inFlashMap = (Map<String, String>)RequestContextUtils.getInputFlashMap(req);
		if(inFlashMap == null || inFlashMap.size() < 1) return;
		
		if(paramMap == null) paramMap = new HashMap<String, String>();
		
		for(String key : inFlashMap.keySet()) {
			String value = inFlashMap.get(key);
			if(StringUtil.isNotEmpty(value)) {
				paramMap.put(key, value);
			}
		}
		
		return;
	}
	
	/**
	 * 현재 요청(또는 세션)하고 있는 지방문화원 코드를 리턴한다. 
	 *  
	 * @param request
	 * @return
	 */
	private String getCurCouncilInfo(HttpServletRequest request, int which) {

		HttpSession session = request.getSession();
		return (String)session.getAttribute( (which == INFO_ID_COUNCIL_CD ? "councilCd" : "councilNm"));
	}
	
	public String getCurCouncilCd(HttpServletRequest request) {
		return getCurCouncilInfo(request, INFO_ID_COUNCIL_CD);
	}
	
	public String getCurCouncilNm(HttpServletRequest request) {
		return getCurCouncilInfo(request, INFO_ID_COUNCIL_NM);
	}

	public void setAlerted(HttpServletRequest request, boolean alerted) {
		NlibLoginVO nlibLoginVO = getNlibLoginVO(request);
		if(nlibLoginVO == null) return;
		
		nlibLoginVO.setAlerted(alerted);
		return;
	}

	public boolean isAlerted(HttpServletRequest request) {
		NlibLoginVO nlibLoginVO = getNlibLoginVO(request);
		if(nlibLoginVO == null) return false;
		
		return nlibLoginVO.isAlerted();
	}
	
	public String getParamStr(Map<String, String> paramMap, String paramName) {
		return getParamStr(paramMap, paramName, null);
	}
	
	public String getParamStr(Map<String, String> paramMap, String paramName, String defValue) {
		if(paramMap == null) return null;
		if(StringUtil.isEmpty(paramName)) return null;
		String value = (String)paramMap.get(paramName);
		
		return StringUtil.isEmpty(value) ? defValue : value;
	}
	
}
