package nlib.cmm.interceptor;

import java.util.HashMap;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import nlib.cmm.service.NlibProperty;
import nlib.user.service.LoginService;
import nlib.util.StringUtil;

/**
 * <pre>
 * @Class Name : NlibInterceptor.java
 * 
 * @Description : 소장자료관 인터셉터로써 지방문화원 접속 정보를 세션에 담기위한 기능을 가짐  
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 8. 31.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 8. 31.
 * @version 1.0
 *
 */
public class NlibInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger log = LoggerFactory.getLogger(NlibInterceptor.class);
	
	@Resource(name = "loginService")
	private LoginService loginService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
		//---------------------------------------
		// 지방문화원 접속 정보를 세션에 담기
		//---------------------------------------
		HttpSession session = request.getSession();
		log.debug("preHandle > sessionid=" + session.getId());
		String councilCd = (String)session.getAttribute("councilCd");
		String councilNm = (String)session.getAttribute("councilNm");
		if(StringUtil.isEmpty(councilCd)) {
			
			// 지방문화원 코드 확인
			String councilDnsHost = StringUtil.getHostName(request.getRequestURL().toString());
			HashMap<String, String> councilInfoMap = loginService.selectCouncilInfoByDnsHost(councilDnsHost);
			councilCd = councilInfoMap.get("councilCd");
			councilNm = councilInfoMap.get("councilNm");

			if(StringUtil.isEmpty(councilCd)) councilCd = NlibProperty.getString("nlib.council.cd");
			if(StringUtil.isEmpty(councilNm)) councilNm = NlibProperty.getString("nlib.council.nm");
			
			session.setAttribute("councilCd"     , councilCd);
			session.setAttribute("councilNm"     , councilNm);
			session.setAttribute("councilDnsHost", councilDnsHost);
		}
		
		return true;
	}
}

