#!/usr/bin/env bash

set -e
set -o nounset
set -o pipefail

SCRIPTS=${SCRIPTS:-$HOME/.local/scripts}
THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename "$THIS_FILE")
THIS=${THIS:-$LOG_LABEL}
LOG_FILE=${LOG_FILE:-"$LOG_LABEL.log"}
FZF_DEFAULT_OPTS=${FZF_DEFAULT_OPTS:-""}

usage() {
  cat <<EOF

Displays a monitor picker and stats preview. This script will accept any fzf options that you'd
like to pass. The id of the monitor is returned from this script upon selection.

USAGE:

  $ $THIS [flags] [FZF_OPTIONS...]

FLAGS:
  --no-default-footer:    Disable the 'Monitors' footer (supplying your own footer disables default as well).
  --no-preview:           Disables the monitor stats preview window.
  -h | --help:            Show this help page.

EOF
}

uses_supplied_footer="0"
no_preview_flag="0"

fzf_opts=("--style=full" "--delimiter=|" "--with-nth=2" "--preview-label=[ Monitor Stats ]")
rows=()
monitor_data=$(hyprctl monitors -j | jq 'sort_by(.id)')

while [[ $# -gt 0 ]]; do
  if [[ $1 =~ ^--footer ]]; then
    uses_supplied_footer="1"
    fzf_opts+=("$1")
  elif [[ $1 == "--no-preview" ]]; then
    no_preview_flag="1"
  elif [[ $1 == "--no-default-footer" ]]; then
    uses_supplied_footer="1"
  elif [[ $1 == "-h" ]] || [[ $1 == "--help" ]]; then
    usage && exit 0
  else
    fzf_opts+=("$1")
  fi
  shift
done

# Logging utility function, use in place of echo.
log() {
  logging log --source "$THIS_FILE" "$@"
}

footer() {
  cat <<'EOF'
   __  ___          _ __             
  /  |/  /__  ___  (_) /____  _______
 / /|_/ / _ \/ _ \/ / __/ _ \/ __(_-<
/_/  /_/\___/_//_/_/\__/\___/_/ /___/
                                     
EOF
}

generate_rows() {
  readarray -t ids <<<"$(echo "$monitor_data" | jq -r '.[] | .id')"
  readarray -t names <<<"$(echo "$monitor_data" | jq -r '.[] | .name')"

  # Zip into rows.
  for i in "${!ids[@]}"; do
    rows+=("${ids[i]}|${names[i]}")
  done
}

################################################################################
# MAIN
################################################################################

# Setup logging file and label.
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

[[ -z ${FZF_DEFAULT_OPTS} ]] &&
  [[ -f $SCRIPTS/catppuccin-colors ]] &&
  source $SCRIPTS/catppuccin-colors

if [[ $uses_supplied_footer == "0" ]]; then
  fzf_opts+=("--footer=$(footer)")
fi

generate_rows
sel=""

# For some reason can't get the preview to work when setting in the fzf_opts array.
if [[ $no_preview_flag == "0" ]]; then
  sel=$(printf '%s\n' "${rows[@]}" | fzf "${fzf_opts[@]}" --preview="$SCRIPTS/hypr/utils/fzf/preview-stats monitor {1}")
else
  sel=$(printf '%s\n' "${rows[@]}" | fzf "${fzf_opts[@]}")
fi

# revove everything but the id portion.
sel=${sel%%|*}
echo "$sel"
