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

Focuses a window, properly handling windows in special workspaces. If no address is supplied,
then we will read address from stdin.

USAGE:
  
    $ $THIS <flags> <address>

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

EOF
}

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

# Prevent hyprctl dispatch calls from printing to the console.
hypr_dispatch() {
  hyprctl dispatch "$@" >/dev/null 2>&1
  return $?
}

focus_window() {
  local address=$1
  log "Focusing window, selection: $address"
  local name=$(hyprctl clients -j | jq -r ".[] | select(.address == \"$address\") | .workspace.name")
  local active_workspace=$(hyprctl activewindow -j | jq -r ".workspace.name")

  log "Window workspace: '$name', active workspace: '$active_workspace'"
  if [[ $name =~ ^special ]] && [[ ! $active_workspace == $name ]]; then
    log "Toggling special workspace prior to focusing window."
    name="${name#special:*}"
    hypr_dispatch togglespecialworkspace $name
  fi
  hypr_dispatch focuswindow "address:$address"
}

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

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

while [[ $# -gt 0 ]]; do
  if [[ $1 == "-h" ]] || [[ $1 == "--help" ]]; then
    usage && exit 0
  else
    address=$1
  fi
  shift
done

if [[ -z $address ]]; then
  log "Reading address from stdin."
  # If an address not supplied then read from stdin, which allows us to pipe the address into
  # this command.
  read -p "Window address: " address
fi

if [[ -z $address ]]; then
  log --error "No address supplied." && exit 1
fi

focus_window $address && exit $?
