package com.huiju.foyo.session;

import com.huiju.foyo.exception.FoyoException;
import com.huiju.foyo.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * 用户session
 * @author weiximei
 */
@Component
@Slf4j
public class UserControl {

    public static final String SESSION_USER = "user";

    /**
     * 设置用户
     * @param user
     */
    public static void setUser(SysUser user) {
        if (null == user) {
            throw new FoyoException("用户信息不能为空");
        }
        HttpSession session = getSession();
        user.setToken(session.getId());
        session.setAttribute(SESSION_USER, user);
        log.info("当前用户sessionId: {}", session.getId());
        SessionLoad.setUser(user);
    }

    /**
     * 获取当前用户
     * @return
     */
    public static SysUser getUser() {
        HttpSession session = getSession();
        log.info("当前用户sessionId: {}", session.getId());

        SysUser sysUser = SessionLoad.getUser();
        if (null == sysUser) {
            throw new FoyoException("用户未登录");
        }

        return sysUser;
    }

    /**
     * 移除用户
     */
    public static void removeUser() {
        HttpSession session = getSession();
        session.removeAttribute(SESSION_USER);
        log.info("当前用户sessionId: {}, 退出登录", session.getId());

        SessionLoad.removeUser();
    }

    /**
     *
     * 获取当前 Request
     *
     */
    private static HttpSession getSession() {
        HttpSession session = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
        return session;
    }
}
