package com.dbs.mplus.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dbs.mplus.MPlusConstants.HOSPITAL;
import com.dbs.mplus.framework.service.ConfigureService;
import com.dbs.mplus.framework.service.RememberMeService;
import com.dbs.mplus.service.mobile.user.repository.dao.MPlusUser;

/**
 * 자동로그인 쿠키
 * 
 * @author jinsukjung
 * 
 */
@Service
public class RememberMeCookieBaker {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private AuthenticationDelegator authDelegator;
	@Autowired 
	private RememberMeService rememberMeService; 
	@Autowired 
	private ConfigureService configureService; 
	
	/**
	 * 자동로그인을 처리해주기 위해서 userName-구분자-password를 쿠키로 구워둔다. 
	 * @param request
	 * @param response
	 * @param userId
	 * @param plainPwd
	 * @param localCipherKey 
	 */
	@SuppressWarnings("unused")
	public void create(HttpServletRequest request, HttpServletResponse response, String userId, String plainPwd, String localCipherKey) {
		String code = HOSPITAL.getCode(this.configureService.getServerServiceAddr(), request.getContextPath()); 
		
		// 정보 굽기 
		this.rememberMeService.create(request, response, code, userId, plainPwd, localCipherKey);
	}
	
	/**
	 * 로그아웃 시 자동로그인 쿠키를 제거합니다
	 * 
	 * @param request
	 * @return
	 */
	public void remove(HttpServletRequest request, HttpServletResponse response) {
		String code = HOSPITAL.getCode(this.configureService.getServerServiceAddr(), request.getContextPath()); 
		this.rememberMeService.remove(request, response, code);
	}
	
	/**
	 * 자동로그인 쿠키가 있으면 세션을 복원합니다
	 * 
	 * @param request
	 * @param response
	 * @param forcedPage 세션복원한 다음에 가야할 곳 
	 * 
	 * @return user : 복원된 사용자 정보 
	 * @throws Exception 복원해서 보니 비번재설정 필요 등 문제가 생긴 경우 
	 */
	public MPlusUser restore(HttpServletRequest request, HttpServletResponse response, String forcedPage) throws Exception {
		String code = HOSPITAL.getCode(this.configureService.getServerServiceAddr(), request.getContextPath()); 
		final String split[] = this.rememberMeService.restore(request, response, code); 
		
		if(split == null) { 
			return null; 
		}
		
		// 복원해서 로그인 처리 
		if (split.length > 1) {
			this.logger.debug("자동 로그인 처리 : " + split[0]);
			return this.authDelegator.authentication(request, response, split[0], split[1], forcedPage);
		}

		return null;
	}
	
}
