import app from "ags/gtk4/app"
import style from "./style.scss"
import Bar from "./Bar"
import Hyprland from "gi://AstalHyprland";
import NotificationPopups from "./notifications/NotificationPopups"

const hyprland = Hyprland.get_default();

function find_main_monitor(): Hyprland.Monitor {
    let monitors = hyprland.get_monitors()
    for (let j = 0; j < monitors.length; j++) {
        for (const monitor of ["eDP", "DP", "HDMI-A"]) {
            for (let i = 0; i < monitors.length; i++) {
                console.log("Checking monitor:", monitors[i].get_name(), "against", monitor + "-" + j)
                if (monitors[i].get_name() == monitor + "-" + j) {
                    return monitors[i]
                }
            }
        }
    }
    return monitors[0]
}

function register_windows(monitor: Hyprland.Monitor) {
    let gtkMonitor = app.get_monitors()[0]
    let scale = (monitor.get_width() >= 3000) ? 1.2 : 1
    Bar(gtkMonitor, scale)
    NotificationPopups()
}

function switch_to_best_monitor() {
    let mainMonitor = find_main_monitor()
    for (var wd of app.get_windows()) {
        wd.destroy();
    }
    register_windows(mainMonitor);
}

hyprland.connect("monitor-added", (_, _monitor: Hyprland.Monitor) => {
    switch_to_best_monitor()
})

hyprland.connect("monitor-removed", () => {
    switch_to_best_monitor()
})

app.start({
    css: style,
    iconTheme: "Papirus",
    main() {
        switch_to_best_monitor()
    },
})
