const css = `${App.configDir}/style.css`;
const hyprland = await Service.import("hyprland");
const systray = await Service.import("systemtray");
const battery = await Service.import("battery");
const audio = await Service.import('audio')

import { NotificationPopups } from "./notifications.js"
import { BatteryPopup } from "./battery.js"
import { cpuProgress, ramProgress } from "./cpu.js"

const laptop = Utils.exec(`hostname`) === "syl";
// const display = Gdk.Display.get_default();
console.log(laptop ? "Running on syl" : "Running on kaladin");

function map_workspaces(id) {
    switch (id) {
    case 1:
        return Widget.Label("");
        break;
    case 2:
        return Widget.Label("");
        break;
    case "browse":
        return Widget.Label("");
        break;
    case 3:
        return Widget.Label("󰈙");
        break;
    case 4:
        return Widget.Label("󰍨");
        break;
    case 5:
        return Widget.Label("");
        break;
    case 9:
        return Widget.Label("");
        break;
    default: 
        return Widget.Label(`${id}`);
    }
}

function workspaces() {
    const active = hyprland.active.workspace.bind("id");
    const workspaces = hyprland.bind("workspaces")
          .as(ws => ws.map(({ id }) => id === -99 ? "" : Widget.Button({
              onClicked: () => hyprland.messageAsync(`dispatch workspace ${id}`),
              child: map_workspaces(id),
              class_name: active.as(i => `${i === id ? "focused" : ""}`),
          })))
    return Widget.Box({
        class_name: "workspaces",
        spacing: 6,
        children: workspaces,
    })
}

function client_name() {
    const client_class = hyprland.active.client.bind("class");
    return Widget.Box({
        class_name: "window-title-box",
        spacing: 6,
        children: [
            Widget.Icon({
                class_name: "client-icon",
                icon: client_class.as(c => `${c === "ff" ? "firefox" : c}`),
            }),
            Widget.Label({
                class_name: "client-title",
                label: hyprland.active.client.bind("title"),
                maxWidthChars: 54,
                truncate: "end",
            }),
        ],
    })
}

function system_tray() {
    /** @param {import('types/service/systemtray').TrayItem} item */
    const systray_item = item => Widget.Button({
        child: Widget.Icon().bind('icon', item, 'icon'),
        tooltipMarkup: item.bind('tooltip_markup'),
        onPrimaryClick: (_, event) => item.activate(event),
        onSecondaryClick: (_, event) => item.openMenu(event),
    });
    return Widget.Box({
        class_name: "systemtray",
        children: systray.bind("items").as(i => i.map(systray_item)),

    })
}

function battery_function() {
    const bat = battery.bind("percent");
    const charging = battery.bind("charging");
    const time_left = battery.bind("time-remaining");
    return Widget.CircularProgress({
        start_at: 0.75,
        rounded: true,
        value: bat.as(p => p / 100),
        class_name: battery.bind("charging").as(c => c ? "battery_dial_charging" : "battery_dial"),
        child: Widget.Icon({
            class_name: "battery_icon",
            icon: battery.bind("icon-name"),
        }),
        tooltip_text: time_left.as(t => "Time till full charge: " + t),
    })
}

const date = Variable("", {
    poll: [1000, 'date "+\%a \%b \%d, \%-I:\%M \%p"'],
})

const expander = Widget.Label({
    hexpand: true,
    label: "",
})

const volume_indicator = Widget.Button({
    on_clicked: () => audio.speaker.is_muted = !audio.speaker.is_muted,
    child: Widget.Icon().hook(audio.speaker, self => {
        const vol = audio.speaker.volume * 100;
        const icon = [
            [101, 'overamplified'],
            [67, 'high'],
            [34, 'medium'],
            [1, 'low'],
            [0, 'muted'],
        ].find(([threshold]) => threshold <= vol)?.[1];

        self.icon = `audio-volume-${icon}-symbolic`;
        self.tooltip_text = `Volume ${Math.floor(vol)}%`;
    }),
})

function Bar(monitor = 0) {
    const myLabel = Widget.Label({
        label: 'some example content',
    })

    const clock = Widget.Label({
        class_name: "clock",
        label: date.bind(),
        truncate: "end",
    })

    return Widget.Window({
        monitor,
        name: `bar${monitor}`, // this name has to be unique
        anchor: [laptop ? 'bottom' : 'top', 'left', 'right'],
        exclusivity: "exclusive",
        margins: [0, 20, 0, 20],
        child: Widget.CenterBox({
            css: laptop ? "margin-bottom: 1em; margin-top: 0.4em" : "margin-bottom: 1em; margin-top: 1em;",
            class_name: "windowbox",
            startWidget: Widget.Box({
                spacing: 0,
                children: [
                    workspaces(),
                    client_name(),
                ],
            }),
            centerWidget: clock,
            endWidget: Widget.Box({
                hexpand: true,
                css: "margin-right: 1em;",
                children: [
                    expander,
                    ramProgress,
                    cpuProgress,
                    volume_indicator,
                    system_tray(),
                    laptop ? battery_function() : null
                ],
            }),
        }),
    })
}

App.config({
    style: css,
    windows: [
        Bar(laptop ? 0 : 0), // can be instantiated for each monitor
        NotificationPopups(),
        (laptop ? BatteryPopup() : null)
    ],
})