package sgc.portal.base.util;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import sgc.portal.SgcPortalAttributes;
import sgc.portal.com.sym.user.model.UserDetails;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * session Util - Spring에서 제공하는 RequestContextHolder 를 이용하여 request 객체를
 * service까지 전달하지 않고 사용할 수 있게 해줌.
 *
 * @author beomgeun.lee
 * @version 1.0.0
 * @since 2020. 6. 14.
 */
public final class SessionUtil {

    /**
     * 생성자 설명.
     */
    private SessionUtil() {
        super();
    }

    /**
     * attribute 값을 가져 오기 위한 method.
     *
     * @param name name
     * @return Obj attribute
     */
    public static Object getAttribute(final String name) {
        return Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getAttribute(name, RequestAttributes.SCOPE_SESSION);
    }

    /**
     * attribute 설정 method.
     *
     * @param name   name
     * @param object Object
     */
    public static void setAttribute(final String name, final Object object) {
        Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).setAttribute(name, object, RequestAttributes.SCOPE_SESSION);
    }

    /**
     * 설정한 attribute 삭제.
     *
     * @param name name
     */
    public static void removeAttribute(final String name) {
        Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).removeAttribute(name, RequestAttributes.SCOPE_SESSION);
    }

    /**
     * session id.
     *
     * @return string string
     */
    public static String getSessionId() {
        return Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
    }

    public static UserDetails getUserDetails() {
        return (UserDetails) SessionUtil.getAttribute(SgcPortalAttributes.AUTHENTICATION);
    }

}