import Hyprland from "gi://AstalHyprland"
import { bind, Variable } from "astal"
import { Gtk } from "astal/gtk4"

function WorkspaceButton(ws: Hyprland.Workspace) {
  const hypr = Hyprland.get_default()

  const classNames = Variable.derive(
    [bind(hypr, "focusedWorkspace"), bind(hypr, "clients")],
    (fws, _) => {
      const classes = []

      const active = fws.id == ws.id

      active && classes.push("active")

      const occupied = hypr.get_workspace(ws.id)?.get_clients()?.length > 0;
      occupied && classes.push("occupied");
      return classes;
    })

  const classes = classNames()

  return (

    <button
      cssClasses={classes}
      onDestroy={() => classNames.drop()}
      // visible={classes.as(cn => cn.includes("occupied") || cn.includes("active"))}
      valign={Gtk.Align.CENTER}
      halign={Gtk.Align.CENTER}
      onClicked={() => ws.focus()}>
    </button>
  )

}

export default function Workspaces() {
  const hypr = Hyprland.get_default()

  return <box cssClasses={["Workspaces"]}>
    {bind(hypr, "workspaces").as((workspaces) =>
      workspaces
        .filter(ws => !(ws.id >= -99 && ws.id < -2))
        .sort((a, b) => a.id - b.id)
        .map((ws) => (
          WorkspaceButton(ws)
        )),
    )}
  </box >

}


