import AstalNetwork from "gi://AstalNetwork"
import { createBinding } from "ags"
import { exec } from "ags/process"

function getIPs(): string {
  try {
    const lan = exec("bash -c \"hostname -I | awk '{print $1}'\"").trim()
    const wan = exec("bash -c \"curl -4 -s --max-time 2 ifconfig.me\"").trim()
    return `LAN: ${lan || "?"}\nWAN: ${wan || "?"}`
  } catch {
    return "IPs unavailable"
  }
}

export default function Network() {
  const net = AstalNetwork.get_default()

  const text = createBinding(net, "primary")((type: AstalNetwork.Primary) => {
    if (type === AstalNetwork.Primary.WIFI) {
      const wifi = net.wifi
      if (!wifi) return "󰤮 offline"
      const ssid = wifi.ssid || "wifi"
      const strength = wifi.strength
      let icon = "󰤯"
      if (strength > 80) icon = "󰤨"
      else if (strength > 60) icon = "󰤥"
      else if (strength > 40) icon = "󰤢"
      else if (strength > 20) icon = "󰤟"
      return `${icon} ${ssid}`
    }
    if (type === AstalNetwork.Primary.WIRED) return "󰈀 wired"
    return "󰤮 offline"
  })

  const cls = createBinding(net, "primary")((type: AstalNetwork.Primary) => {
    if (type === AstalNetwork.Primary.WIFI) return "network module wifi"
    if (type === AstalNetwork.Primary.WIRED) return "network module wired"
    return "network module disconnected"
  })

  return (
    <eventbox
      onHover={(self) => {
        self.tooltipText = getIPs()
      }}
    >
      <label class={cls} label={text} hasTooltip />
    </eventbox>
  )
}
