package cn.lihongjie.coal.common;

import cn.lihongjie.coal.session.service.SessionService;
import cn.lihongjie.coal.user.dto.UserDto;

import lombok.Getter;
import lombok.experimental.UtilityClass;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@UtilityClass
public class Ctx {

    @Getter
    private static ConfigurableApplicationContext context;

    public static String getUserId() {
        if (!isLoggedIn()) {
            return null;
        }
        return getAuthentication().getUser().getId();
    }

    public static boolean isLoggedIn() {

        return getAuthentication() != null && getAuthentication().isAuthenticated();
    }

    public static String getSessionId() {
        if (!isLoggedIn()) {
            return null;
        }
        return getAuthentication().getSessionId();
    }

    private static SessionService.MyAuthentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if( ! (authentication instanceof SessionService.MyAuthentication))
            return null;


        return (SessionService.MyAuthentication)
                authentication;
    }

    public static boolean isOrgAdmin() {

        return isLoggedIn() && getAuthentication().getUser().getOrgAdmin();
    }

    public static boolean isSysAdmin() {

        return isLoggedIn() && getAuthentication().getUser().getSysAdmin();
    }

    public static UserDto currentUser() {
        if (!isLoggedIn()) {
            return null;
        }
        return  getAuthentication().getUser();
    }

    public static void setContext(ConfigurableApplicationContext context) {
        Ctx.context = context;
    }
}
