#!/usr/bin/env bash

# Returns 0 if $1 is a command available on PATH; used to guard optional tools.
check() {
  command -v "$1" 1>/dev/null
}

# Wrapper: use notify-send when available, fall back to stdout.
# -a sets the application name shown in the notification bubble.
notify() {
  check notify-send && {
    notify-send -a "Color Picker" "$@"
    return
  }
  echo "$@"
}

# Persistent cache directory and colour-history file.
# The || chain only runs the creation command when the path does not yet exist.
loc="$HOME/.cache/colorpicker"
[ -d "$loc" ] || mkdir -p "$loc"
[ -f "$loc/colors" ] || touch "$loc/colors"

# Maximum number of recent colours kept in the history file.
limit=10

# -l mode: dump the raw colour list to stdout (consumed by other scripts or widgets).
[[ $# -eq 1 && $1 = "-l" ]] && {
  cat "$loc/colors"
  exit
}

# -j mode: emit a Waybar custom-module JSON payload.
# The most recently picked colour becomes the icon tint; all colours appear in the tooltip.
[[ $# -eq 1 && $1 = "-j" ]] && {
  # The most-recently picked colour is always stored on the first line.
  text="$(head -n 1 "$loc/colors")"

  # mapfile reads remaining lines into an indexed array, avoiding word-splitting issues.
  mapfile -t allcolors < <(tail -n +2 "$loc/colors")
  # allcolors=($(tail -n +2 "$loc/colors"))
  tooltip="<b>   COLORS</b>\n\n"

  # Mark the newest colour with an arrow; the Pango <span> colours a Nerd-Font swatch glyph.
  tooltip+="-> <b>$text</b>  <span color='$text'></span>  \n"
  for i in "${allcolors[@]}"; do
    tooltip+="   <b>$i</b>  <span color='$i'></span>  \n"
  done

  # Waybar expects a single-line JSON object on stdout.
  cat <<EOF
{ "text":"<span color='$text'></span>", "tooltip":"$tooltip"}
EOF

  exit
}

# Guard: hyprpicker must be installed — it is the Wayland screen colour-picker tool.
check hyprpicker || {
  notify "hyprpicker is not installed"
  exit
}
# Kill any stale hyprpicker instance before launching a new one; -q suppresses "no process" errors.
killall -q hyprpicker
color=$(hyprpicker)

# Copy the picked hex colour to the Wayland clipboard.
# sed -z treats the whole input as NUL-terminated, removing the trailing newline in one pass.
check wl-copy && {
  echo "$color" | sed -z 's/\n//g' | wl-copy
}

# Rotate the history: write the new colour first, then append the previous (limit-1) entries.
prevColors=$(head -n $((limit - 1)) "$loc/colors")
echo "$color" >"$loc/colors"
echo "$prevColors" >>"$loc/colors"
# Strip blank lines produced by the rotation when the file was shorter than limit.
sed -i '/^$/d' "$loc/colors"
# Send RTMIN+1 real-time signal to Waybar so it re-polls this custom module immediately.
pkill -RTMIN+1 waybar
