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

function formatTime(): string {
  const now = new Date()
  return now.toLocaleTimeString("fr-FR", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  })
}

function formatDate(): string {
  const now = new Date()
  return now.toLocaleDateString("fr-FR", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  })
}

function formatDateShort(): string {
  const now = new Date()
  return now.toLocaleDateString("fr-FR", {
    weekday: "short",
    day: "numeric",
    month: "short",
  })
}

function getCalendar(): string {
  try {
    return exec("bash -c \"cal -h\"").trim()
  } catch {
    return ""
  }
}

function getUptime(): string {
  try {
    return exec("bash -c \"uptime -p | sed 's/up //'\"").trim()
  } catch {
    return ""
  }
}

function buildTooltip(): string {
  const full = formatDate()
  const cal = getCalendar()
  const up = getUptime()
  return `${full}\n\n${cal}\n\n⏱ uptime: ${up}`
}

export default function Clock() {
  const time = createPoll("", 1000, () => formatTime())
  const date = createPoll("", 60000, () => formatDateShort())

  return (
    <box>
      <label class="clock" label={time} />
      <label class="separator" label="│" />
      <eventbox
        onHover={(self) => {
          self.tooltipText = buildTooltip()
        }}
      >
        <label class="date" label={date} hasTooltip />
      </eventbox>
    </box>
  )
}
