#!/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}

uses_supplied_footer="0"
fzf_opts=()
rows=()
workspace_id=""

usage() {
  cat <<EOF

Select from currently available windows, returning the selected window's address.

USAGE:

  $ $THIS <flags> [FZF_OPTIONS]

FLAGS:
  -w | --workspace <id>:    Only show windows for the given workspace.
  -h | --help:              Show this help page.

NOTES:

By default, we show a footer and header unless specifically passed in as extra arguments / options.
Any other options or arguments are passed directly to 'fzf'.

EOF
}

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

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

generate_rows() {
  local addresses=()

  if [[ -n $workspace_id ]]; then
    addresses=$(hyprctl clients -j | jq -r ".[] | select(.workspace.id == $workspace_id) | .address")
  else
    addresses=$(hyprctl clients -j | jq -r ".[] | .address")
  fi

  for address in $addresses; do
    title=$(hyprctl clients -j | jq -r ".[] | select(.address == \"$address\") | .title")
    # Replace in occurrences of what we use as delimiter in the title, so they're presented
    # correctly.
    title=${title//|/-}
    rows+=("$address|$title")
  done
}

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

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

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

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

generate_rows

sel=$(
  printf '%s\n' "${rows[@]}" |
    fzf --style=full "${fzf_opts[@]}" \
      --preview-label='[ Window Stats ]' --delimiter='|' --with-nth=2 \
      --preview='$SCRIPTS/hypr/utils/fzf/preview-stats window {1}'
)
status=$?

[[ -z $sel ]] && exit 1

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