import { App, Astal, Gtk, Gdk, Widget, astalify } from "astal/gtk4"
import { GLib, Variable } from "astal"
import Hyprland from "gi://AstalHyprland"
import Tray from "gi://AstalTray"
import Battery from "gi://AstalBattery"
import Network from "gi://AstalNetwork"
import AstalTray from "gi://AstalTray?version=0.1"


type Workspace = {
  id: number
  focus: () => void
}

type Hyprland = {
  workspaces: Workspace[]
  focusedWorkspace: Workspace | null
}

function Bat() {
  const bat = Battery.get_default()

  return <box cssClasses={["Battery"]}>
    Battery: {bat.get_percentage() * 100}%
  </box>

}

function Net() {
  const network = Network.get_default()

  return <box cssClasses={["Network"]} >
    {network.wifi.enabled}
  </box>
}

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

  return <box cssClasses={["Workspaces"]} >
    {
      hypr.workspaces.filter(ws => !(ws.id >= -99 && ws.id < -2))
        .sort((a, b) => a.id - b.id)
        .map(ws => (
          <button
            cssClasses={
              ws === hypr.focusedWorkspace ? ["focused"] : []}
            onClicked={() => ws.focus()}>
            {ws.id}
          </button>
        ))
    }
  </box >
}

function SysTray() {
  const tray = AstalTray.get_default()

  print(tray.get_items.length)

  return <box
    cssClasses={["SysTray"]}
  >
    {tray.get_items().map(item => (
      <menubutton
        tooltipMarkup={item.tooltipMarkup}
        menuModel={item.menuModel}
      >
        <image gicon={item.get_gicon()} />
      </menubutton>
    ))}
  </box>
}

function Time({ }) {
  const time = Variable<string>("").poll(1000, () => GLib.DateTime.new_now_local().format("%H:%M")!)

  return <label
    cssName="Time"
    onDestroy={() => time.drop()}
    label={time()} />
}
export default function Bar(gdkmonitor: Gdk.Monitor) {
  const { TOP, LEFT, RIGHT } = Astal.WindowAnchor

  return <window
    visible
    cssClasses={["Bar"]}
    gdkmonitor={gdkmonitor}
    exclusivity={Astal.Exclusivity.EXCLUSIVE}
    anchor={TOP | LEFT | RIGHT}
    application={App}>
    <centerbox>
      <box hexpand halign={Gtk.Align.START}>
        <Bat />
        <SysTray />
      </box>
      <box hexpand halign={Gtk.Align.CENTER}>
        <Workspaces />
      </box>
      <box hexpand halign={Gtk.Align.END}>
        <Net />
        <Time />
      </box>

    </centerbox>
  </window>
}
