#!/bin/bash

# omarchy:summary=Minimize a window to the dock
# omarchy:args=[window-address]

# The active window when given no address. Minimized windows wait on a special
# workspace, and the dock brings them back.
if [[ -n ${1:-} ]]; then
  ADDRESS=$1
  WORKSPACE=$(hyprctl clients -j | jq -r --arg address "$ADDRESS" 'first(.[] | select(.address == $address) | .workspace.id) // empty')
else
  read -r ADDRESS WORKSPACE < <(hyprctl activewindow -j | jq -r '"\(.address // "") \(.workspace.id // "")"')
fi

[[ -n $ADDRESS && $WORKSPACE =~ ^[0-9]+$ ]] || exit 1

# Only floating workspaces have the dock to bring a window back from.
[[ $(omarchy-hyprland-workspace-layout-current "$WORKSPACE") == "floating" ]] || exit 0

remember_minimized_from() {
  local address=$1 workspace=$2 clients tag
  if clients=$(hyprctl clients -j); then
    while read -r tag; do
      [[ $tag =~ ^omarchy-minimized-from-[0-9]+$ && $tag != "omarchy-minimized-from-$workspace" ]] || continue
      hyprctl dispatch "hl.dsp.window.tag({ tag = \"-$tag\", window = \"address:$address\" })" >/dev/null
    done < <(jq -r --arg address "$address" '.[] | select(.address == $address) | (.tags // [])[]' <<<"$clients")
  fi
  hyprctl dispatch "hl.dsp.window.tag({ tag = \"+omarchy-minimized-from-$workspace\", window = \"address:$address\" })" >/dev/null
}

remember_minimized_from "$ADDRESS" "$WORKSPACE"
hyprctl dispatch "hl.dsp.window.move({ workspace = \"special:minimized\", follow = false, window = \"address:$ADDRESS\" })" >/dev/null

# Focus would otherwise stay with the minimized window, and the next window
# opened would join it on the hidden workspace.
hyprctl dispatch "hl.dsp.focus({ workspace = \"$WORKSPACE\" })" >/dev/null
