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

return_name_if_special_flag="0"
return_name_flag="0"

usage() {
  cat <<EOF

Select from currently available workspaces. If no options are specified, then the default behavior is 
to return the selected workspace id.

USAGE:

  $ $THIS <flags> [FZF_OPTIONS]

FLAGS:

  -n | --return-name:               Return workspace name instead of id.

  -s | --return-name-if-special:    Return name if a special workspace, otherwise return the id.
                                    This option is useful when moving a workspace using 'hyprctl' with
                                    the selection.

  -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
}

prompt_for_selection() {

  local rows=()
  local fzf_opts=$1
  local sel=""

  for id in $(hyprctl workspaces -j | jq 'sort_by(.id)' | jq 'reverse' | jq -r '.[] | .id'); do
    name=$(hyprctl workspaces -j | jq -r ".[] | select(.id == $id) | .name")
    rows+=("$id|$name")
  done

  log "Showing workspace picker / stats..."

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

  echo "$sel"
}

parse_return_val() {
  local sel=""
  read -r sel

  if [[ -z $sel ]]; then
    log --error "Selection was empty." && exit 1
  fi
  local name=${sel##*\|}
  local id=${sel%%\|*}

  if [[ $return_name_flag == "1" ]] ||
    ([[ $return_name_if_special_flag == "1" ]] && [[ $name =~ ^special ]]); then
    # Return only the name portion of the selection.
    echo "$name"
  else
    # Return only the id portion of the selection.
    echo "$id"
  fi
}

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

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

uses_supplied_footer="0"
fzf_opts=()

while [[ $# -gt 0 ]]; do
  if [[ $1 == "-h" ]] || [[ $1 == "--help" ]]; then
    usage && exit 0
  elif [[ $1 == "-n" ]] || [[ $1 == "--return-name" ]]; then
    return_name_flag="1"
  elif [[ $1 == "-s" ]] || [[ $1 == "--return-name-if-special" ]]; then
    return_name_if_special_flag="1"
  elif [[ $1 =~ ^--footer ]]; then
    uses_supplied_footer="1"
    fzf_opts+=("$1")
  else
    fzf_opts+=("$1")
  fi
  shift
done

# Load fzf color scheme if it's not been setup yet.
[[ -z ${FZF_DEFAULT_OPTS} ]] &&
  [[ -f $SCRIPTS/catppuccin-colors ]] &&
  source $SCRIPTS/catppuccin-colors

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

prompt_for_selection "${fzf_opts[@]}" | parse_return_val
