package com.codvision.auth.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.codvision.auth.core.token.ITokenManager;
import com.codvision.auth.entity.vo.SysUserVO;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.service.IAuthService;
import com.codvision.authcore.util.AuthUtil;
import com.codvision.authcore.util.RequestUtil;
import com.codvision.commoncore.exception.AuthException;
import org.springframework.context.ApplicationContext;

import java.util.Optional;


/**
 * @author codvision
 */
public class UserContext {

    public static SysUserVO get() {
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        return BeanUtil.toBean(sysUser, SysUserVO.class);
    }

    /**
     * 重置当前用户信息
     *
     * @param sysUserVO 用户信息
     */
    public static SysUserBean set(SysUserVO sysUserVO) {
        ApplicationContext context = SpringUtil.getApplicationContext();
        if (!context.containsBean("authService")) {
            return new SysUserBean();
        }
        IAuthService authService = SpringUtil.getBean(IAuthService.class);
        String token = authService.getAuthToken(RequestUtil.getRequest());
        Optional.ofNullable(token).orElseThrow(() -> new AuthException(10002));

        SysUserBean sysUser = BeanUtil.toBean(sysUserVO, SysUserBean.class);
        SpringUtil.getBean(ITokenManager.class).setTokenUser(token, sysUser);
        return sysUser;
    }

    /**
     * 移除当前用户
     */
    public static void remove() {
        ApplicationContext context = SpringUtil.getApplicationContext();
        if (!context.containsBean("authService")) {
            return;
        }
        IAuthService authService = SpringUtil.getBean(IAuthService.class);
        String token = authService.getAuthToken(RequestUtil.getRequest());
        Optional.ofNullable(token).orElseThrow(() -> new AuthException(10002));

        SpringUtil.getBean(ITokenManager.class).removeTokenUser(token);
    }
}
