#!/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
Toggle the visibility of all windows on the active workspace.

USAGE:

  $ $THIS <flags>

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

EOF
}

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

# Suppress output from hyprctl
hypr_dispatch() {
  hyprctl dispatch "$@" >/dev/null 2>&1
}

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

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

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

# Workspace to hide everything in
HIDE_WS="special:hidden"

# File to store original workspace ID
STATE_FILE="/tmp/hypr_hide_state"

# Get current workspace ID
CUR_WS=$(hyprctl -j activeworkspace | jq -r '.id')

# Check if we're currently hidden
if [[ -f "$STATE_FILE" ]]; then
  # Restore windows
  ORIG_WS=$(cat "$STATE_FILE")
  log "Restoring windows to: '$ORIG_WS'"
  for win in $(hyprctl -j clients | jq -r ".[] | select(.workspace.name | contains(\"$HIDE_WS\")) | .address"); do
    hyprctl dispatch movetoworkspace "$ORIG_WS,address:$win"
    hyprctl dispatch workspace "$ORIG_WS"
  done
  rm "$STATE_FILE"
else
  log "Hiding windows from: '$CUR_WS'"
  # Hide all windows (move to special hidden workspace)
  for win in $(hyprctl -j clients | jq -r ".[] | select(.workspace.id == $CUR_WS) | .address"); do
    hyprctl dispatch movetoworkspace "$HIDE_WS,address:$win"
    hyprctl dispatch togglespecialworkspace "$HIDE_WS"
  done

  [[ -f "$STATE_FILE" ]] && rm "$STATE_FILE"
  echo "$CUR_WS" >"$STATE_FILE"
fi
