#!/usr/bin/env bash

set -e
set -o nounset
set -o pipefail

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

usage() {
  cat <<EOF

Utility for performing actions on windows.

USAGE:

  $ $THIS <command> <flags>

FLAGS:
  -h | --help:          Show this page.

COMMANDS:
  action:               Action picker, to perform actions on a given window.
  close:                Close window(s).
  focus:                Focuses a window, handling special workspaces properly.
  launch:               Launches an interactive picker in a new terminal.
  picker:               Window picker that prompts for an action to perform on the window.
  toggle-floating:      Toggles floating property of a window.

Run "$THIS <command> --help" for more information on a command.

EOF
}

window_class="com.ghostty.$THIS"
window_padding_x="10"

log() {
  logging log --source "$THIS_FILE" "$@"
}

launch_usage() {
  cat <<EOF

Launches an interactive picker in a new terminal window.

USAGE:
  
  $ $THIS launch <flags>


FLAGS:
  -h | --help:                      Show this page.

EOF
}

# Launch in a new terminal window.
launch() {
  if [[ $@ =~ ^-h ]] || [[ $@ =~ ^--help ]]; then
    launch_usage && exit 0
  fi

  log "Launching terminal."

  ghostty --class="$window_class" --window-padding-x="$window_padding_x" \
    --keybind="ctrl+c=quit" \
    -e "${BASH_SOURCE[0]}" "$@"
}

show_picker() {
  log "Showing picker..."
  THIS="$THIS picker" "$SCRIPTS/hypr/utils/windows/windowctl-picker" "$@"
  return $?
}

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

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

while [[ $# -gt 0 ]]; do
  if [[ $1 == "action" ]]; then
    shift
    THIS="$THIS action" "$SCRIPTS/hypr/utils/windows/window-action-picker" "$@"
    exit $?
  elif [[ $1 == "close" ]]; then
    shift
    THIS="$THIS close" "$SCRIPTS/hypr/utils/windows/close-windows" "$@"
    exit $?
  elif [[ $1 == "focus" ]]; then
    shift
    THIS="$THIS focus" "$SCRIPTS/hypr/utils/windows/focus-window" "$@"
    exit $?
  elif [[ $1 == "launch" ]]; then
    shift
    if [[ -z $1 ]]; then
      launch picker
    else
      launch "$@"
    fi
    exit 0
  elif [[ $1 == "picker" ]]; then
    shift
    show_picker "$@"
    exit $?
  elif [[ $1 == "toggle-floating" ]]; then
    shift
    THIS="$THIS toggle-floating" "$SCRIPTS/hypr/utils/windows/window-toggle-floating" "$@"
    exit $?
  elif [[ $1 == "-h" ]] || [[ $1 == "--help" ]]; then
    usage && exit 0
  else
    log --error "Unhandled arg: $1"
    exit 1
  fi
  shift
done

# If we've reached here then no commands were passed / handled.
usage && exit 1
