#!/usr/bin/env bash

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

usage() {
  cat <<EOF

Switch to the given workspace. Toggling off a special workspaces if active window is on a
special workspace.

The builtin way in hyprland does not toggle off special workspaces, so the workspace just
changes underneath the special workspace, whereas this script ensures that you switch to
the workspace.

USAGE:


$ $THIS <flags> <workspace>

FLAGS:
  -p | --previous:          Switch to the previously active workspace.
  -t | --to <workspace>:    Workspace to switch to.
  -h | --help:              Show this help page.

EOF
}

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

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

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

target_workspace=""
active_workspace=$(hyprctl activewindow -j | jq -r '.workspace.name')

while [[ $# -gt 0 ]]; do
  if [[ $1 =~ ^-h ]] || [[ $1 =~ ^--help ]]; then
    usage && exit 0
  elif [[ $1 =~ ^-t ]] || [[ $1 =~ ^--to ]]; then
    target_workspace=$1
  elif [[ $1 =~ ^-p ]] || [[ $1 =~ ^--previous ]]; then
    target_workspace="previous"
  else
    target_workspace=$1
  fi
  shift
done

# Read from stdin if no workspace was supplied.
if [[ -z $target_workspace ]]; then
  read -p "Workspace: " target_workspace
fi

if [[ -z target_workspace ]]; then
  log --error "Must supply a workpsace to switch to."
  usage && exit 1
fi

# If active window is on a special workspace, then toggle the special workspace off.
if [[ $active_workspace =~ ^special ]]; then
  log "Toggling special workspace: '$active_workspace'"
  hyprctl dispatch togglespecialworkspace ${active_workspace#special:} >/dev/null 2>&1

  # Only toggle the special workspace if trying to switch to previous and we're currently
  # on a special workspace.
  if [[ $target_workspace == "previous" ]]; then
    exit 0
  fi
fi

log "Switching to workspace: $target_workspace"
hyprctl dispatch workspace $target_workspace >/dev/null 2>&1
