package kr.iotdoor.boot.web;

import kr.iotdoor.boot.config.IotdoorProperties;
import kr.iotdoor.boot.model.user.AdminUserPrincipal;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.List;

@ControllerAdvice(annotations = Controller.class)
public class GlobalViewModelAdvice {

    private final IotdoorProperties properties;

    public GlobalViewModelAdvice(IotdoorProperties properties) {
        this.properties = properties;
    }

    @ModelAttribute("siteInfo")
    public IotdoorProperties.Site siteInfo() {
        return properties.getSite();
    }

    @ModelAttribute("popupList")
    public List<Object> popupList() {
        return List.of();
    }

    @ModelAttribute("subMainClass")
    public String subMainClass() {
        return "";
    }

    @ModelAttribute("currentAdminName")
    public String currentAdminName(Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) {
            return "";
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof AdminUserPrincipal adminUserPrincipal) {
            return adminUserPrincipal.getDisplayName();
        }
        return properties.getSecurity().getAdminDisplayName();
    }
}
