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

usage() {
  cat <<EOF

Utility for getting fzf preview data.

USAGE:

  $ $THIS [COMMAND] [ARG...]

COMMAND:

  monitor <id> <keys>:            Get monitor data, optionally providing keys to return.
  window <address> <keys>:        Get window data, optionally providing keys to return.
  workspace <id> <keys>:          Get workspace data, optionally providing keys to return.
  utlis <name> <config>:          Get utils-launcher data.

EXAMPLE:

Here's an example of getting window data, but only returning "title", "workspace", and "address".

  $ $THIS window "0xaaaaea92a7e0" "{title, workspace, address}"

EOF
}

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

call_jq() {
  hypr_path=$1
  select_str=$2
  optional_keys=$3

  if [[ -n $optional_keys ]]; then
    hyprctl $hypr_path -j | jq -C ".[] | $select_str | $optional_keys"
  else
    hyprctl $hypr_path -j | jq -C ".[] | $select_str"
  fi
}

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

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

# Early out check for help flag
if [[ $@ =~ -h ]] || [[ $@ =~ --help ]]; then
  usage && exit 0
# Check for expected argument count or error.
elif [[ ! $# -ge 2 ]] || [[ $# -gt 3 ]]; then
  log --error "Unexpected argument count, expected 2 or 3 but got '$#'"
  exit 1
fi

mode=${1:-""}
arg=${2:-""}
arg2=${3:-""} # either optional keys or utils config.

if [[ $mode == "monitor" ]]; then
  call_jq monitors "select(.id == $arg)" "$arg2"
elif [[ $mode == "window" ]]; then
  call_jq clients "select(.address == \"$arg\")" "$arg2"
elif [[ $mode == "workspace" ]]; then
  call_jq workspaces "select(.id == $arg)" "$arg2"
elif [[ $mode == "utils" ]]; then
  config="${arg2//\'/}"
  if [[ ! -f $config ]]; then
    log --error "No utility-launcher config found: $config"
    exit 1
  fi
  desc=$(jq -C ".[] | select(.name == \"$arg\") | .description" $config)
  exec=$(jq -C ".[] | select(.name == \"$arg\") | .exec" $config)
  echo -e "\n${desc[@]}\n\n" | fmt -w ${FZF_PREVIEW_COLUMNS:-80}
  echo -e "\e[31mEXEC:\e[0m $exec\n"
else
  log --error "Unexpected mode: $mode"
  usage && exit 1
fi
