package cn.reghao.devops.mgr.admin.service;

import cn.reghao.devops.mgr.admin.security.form.AccountAuthToken;
import cn.reghao.devops.mgr.admin.model.po.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author reghao
 * @date 2023-12-01 10:31:52
 */
public class UserContext {
    public static String getUsername() {
        User user = getUser();
        if (user == null) {
            return null;
        }

        return user.getScreenName();
    }

    public static User getUser() {
        Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
        if (authToken instanceof AccountAuthToken) {
            return (User) authToken.getDetails();
        }

        return null;
    }

    public static int getUserId() {
        Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
        if (authToken instanceof AccountAuthToken) {
            User user = (User) authToken.getDetails();
            return user.getId();
        }

        return -1;
    }

    public static String getUserRole() {
        User user = getUser();
        if (user != null) {
            return user.getRole().getName();
        }

        return "";
    }

    /*public static Set<String> getUserRoles() {
        User user = getUser();
        if (user != null) {
            return user.getRole();
        }

        return Collections.emptySet();
    }*/
}
