package com.style24.front.support.security.session;

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

import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.style24.front.support.security.TsfLoginDetails;
import com.style24.persistence.domain.Login;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.security.GagaSession;

/**
 * Session
 * 
 * @author gagamel
 * @since 2020. 9. 11
 */
@Slf4j
public class TsfSession extends GagaSession {

	/**
	 * Get Session Info.
	 * @return 세션 정보
	 */
	public static Login getInfo() {
		TsfLoginDetails loginDetails = (TsfLoginDetails)RequestContextHolder.currentRequestAttributes().getAttribute("session", RequestAttributes.SCOPE_SESSION);

		if (loginDetails == null)
			return null;

		return loginDetails.getLoginInfo();
	}

	/**
	 * 로그인 여부
	 * @return true/false
	 */
	public static boolean isLogin() {
		TsfLoginDetails loginDetails = (TsfLoginDetails)RequestContextHolder.currentRequestAttributes().getAttribute("session", RequestAttributes.SCOPE_SESSION);

		if (loginDetails == null)
			return false;

		return loginDetails.isLogin();
	}

	/**
	 * 프론트구분 가져오기
	 * @return P:PC, M:모바일
	 */
	public static String getFrontGb() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Device device = DeviceUtils.getCurrentDevice(request);

		if (device == null) {
			log.debug("device is null");
			return "P";
		}

		log.debug("device.isMobile: {}", device.isMobile());
		log.debug("device.isNormal: {}", device.isNormal());
		log.debug("device.isTablet: {}", device.isTablet());

		return device.isMobile() ? "M" : "P";
	}

	/**
	 * 세션 설정
	 * @param name - 명칭
	 * @param value - 값
	 * @return HttpServletResponse
	 */
	public static void setAttribute(String name, String value) {
		HttpServletRequest request = getHttpServletRequest();
		request.getSession(true).setAttribute(name, value);
	}

	/**
	 * 세션 값 조회
	 * @return 세션 값
	 */
	public static String getAttribute(String name) {
		HttpServletRequest request = getHttpServletRequest();
		HttpSession session = request.getSession(true);

		if (session != null && session.getAttribute(name) != null) {
			return (String)session.getAttribute(name);
		}

		return "";
	}

}
