import { bind } from "astal"
import Hyprland from "gi://AstalHyprland"

export default function Workspaces(props: { monitor: string, iconSide: "left" | "right" }) {
    const hyprland = Hyprland.get_default();

    return <box className={`pill Workspaces icon-${props.iconSide}`}>
        {props.iconSide == "left" && <label className="icon" label="󱗼" />}
        <box className="label">
            {bind(hyprland, "workspaces").as(wss => wss
                .filter(it => it && it.get_monitor && it.get_monitor().name == props.monitor)
                .sort((a, b) => a.get_id() - b.get_id())
                .map(workspace => <Workspace workspace={workspace} />)
            )}
            <button
                className="add"
                onClick={() => {
                    hyprland.dispatch("workspace", "emptynm");
                }}
            >
                <label label="" />
            </button>
        </box>
        {props.iconSide == "right" && <label className="icon" label="󱗼" />}
    </box>
}

function Workspace(props: { workspace: Hyprland.Workspace }) {
    const hyprland = Hyprland.get_default();

    return <box>
        {bind(props.workspace.get_monitor(), "activeWorkspace").as(ws => {
            if (ws == props.workspace) {
                return <label
                    label=""
                />
            } else {
                return <button
                    onClick={() => {
                        const name = props.workspace.name
                        if (name) {
                            hyprland.dispatch("workspace", `name:${name}`);
                        } else {
                            hyprland.dispatch("workspace", `id:${props.workspace.get_id()}`);
                        }
                    }}
                >
                    <label
                        label=""
                    />
                </button>
            }
        })}
    </box>
}
