import { createPoll } from "ags/time"
import { exec } from "ags/process"

function getCpuUsage(): string {
  try {
    const out = exec("bash -c \"top -bn1 | grep 'Cpu(s)' | awk '{print 100 - $8}'\"")
    return `${Math.round(parseFloat(out))}`
  } catch {
    return "?"
  }
}

function getRamUsage(): string {
  try {
    return exec("bash -c \"free | awk '/Mem:/ {printf \\\"%.0f\\\", $3/$2 * 100}'\"")
  } catch {
    return "?"
  }
}

export default function SystemStats() {
  const cpu = createPoll("0", 3000, () => getCpuUsage())
  const ram = createPoll("0", 5000, () => getRamUsage())

  return (
    <box>
      <label class="cpu module" label={cpu((v: string) => ` ${v}%`)} />
      <label class="ram module" label={ram((v: string) => `󰍛 ${v}%`)} />
    </box>
  )
}
