#!/bin/sh

app="$1"
command="$2"

tree=$(swaymsg -t get_tree) || exit 1

# Identifiants complets, sans distinction de casse ; "|" permet les alias.
windows=$(printf '%s\n' "$tree" | jq -r --arg app "$app" '
  recurse(.nodes[], .floating_nodes[])
  | select(
      ((.app_id // "") | test("^(" + $app + ")$"; "i")) or
      ((.window_properties.class // "") | test("^(" + $app + ")$"; "i"))
    )
  | .id
') || exit 1

# Aucune fenêtre : lancer l'application
if [ -z "$windows" ]; then
    exec swaymsg exec "$command"
fi

# Récupère la fenêtre actuellement focalisée
focused=$(printf '%s\n' "$tree" | jq -r '
  recurse(.nodes[], .floating_nodes[])
  | select(.focused == true)
  | .id
') || exit 1

# Transforme la liste en tableau
set -- $windows

# Cherche la fenêtre suivante après celle qui est actuellement focus
next=""
found=0

for id in "$@"; do
    if [ "$found" = 1 ]; then
        next="$id"
        break
    fi

    if [ "$id" = "$focused" ]; then
        found=1
    fi
done

# Si on était sur la dernière fenêtre, revenir à la première
if [ -z "$next" ]; then
    next="$1"
fi

swaymsg "[con_id=$next] focus"
