#!/bin/bash

# omarchy:summary=Print monitor panel state for the shell
# omarchy:group=monitor

# Hyprland reports `mirrorOf` as the mirrored monitor's id, so name it here
# for everything below and for the panel.
monitors_json=$(hyprctl monitors all -j | jq '
  (map({key: (.id | tostring), value: .name}) | from_entries) as $names
  | map(.mirrorOf = (if (.mirrorOf // "none") == "none" then "none" else ($names[.mirrorOf | tostring] // .mirrorOf) end))
')
focused_monitor=$(printf '%s\n' "$monitors_json" | jq -r '[.[] | select(.focused == true)][0].name // ""')

# Read every enabled display's brightness at once: a DDC read takes a moment
# per monitor, so one after another they'd add up.
brightness_dir=$(mktemp -d)
trap 'rm -rf "$brightness_dir"' EXIT
while read -r name; do
  [[ $name =~ ^[A-Za-z0-9._-]+$ ]] || continue
  { omarchy-brightness-display --monitor "$name" 2>/dev/null; echo; } | head -n 1 >"$brightness_dir/$name" &
done < <(printf '%s\n' "$monitors_json" | jq -r '.[] | select(.disabled != true) | .name')
wait

if [[ -n $focused_monitor && -f $brightness_dir/$focused_monitor ]]; then
  cat "$brightness_dir/$focused_monitor"
else
  echo
fi

printf '%s\n' "$monitors_json" | jq -r '
  def internal: test("^(eDP|LVDS|DSI)-");
  ([.[] | select(.name | internal)][0].name // ""),
  ([.[] | select((.name | internal) | not)][0].name // ""),
  ([.[] | select((.name | internal) and .disabled != true)][0].name // ""),
  ([.[] | select(.mirrorOf != "none") | if (.name | internal) then .mirrorOf else .name end][0] // "")
'

printf '%s\n' "$focused_monitor"
omarchy-hyprland-monitor-scaling 2>/dev/null || echo

brightness_json=$(for file in "$brightness_dir"/*; do
  [[ -f $file ]] && printf '%s\t%s\n' "${file##*/}" "$(<"$file")"
done | jq -R -n '[inputs | split("\t") | select(.[1] | test("^[0-9]+$")) | {(.[0]): (.[1] | tonumber)}] | add // {}')

printf '%s\n' "$monitors_json" | jq -c --argjson brightness "$brightness_json" \
  '[.[] | {name, make, model, enabled:(.disabled != true), focused:(.focused == true), width, height, refreshRate, scale, x, y, transform, mirrorOf, availableModes:(.availableModes // []), brightness:($brightness[.name] // null)}]'

# Whether the mirror is Omarchy's own, which the panel can turn back off.
if omarchy-hyprland-toggle-enabled internal-monitor-mirror; then
  echo on
else
  echo
fi
