#!/bin/sh

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

# Récupère les conteneurs correspondant à l'application.
windows=$(swaymsg -t get_tree | jq -r --arg app "$app" '
  recurse(.nodes[], .floating_nodes[])
  | select(
      (.app_id == $app) or
      (.window_properties.class == $app)
    )
  | .id
')

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

# Récupère la fenêtre actuellement focalisée
focused=$(swaymsg -t get_tree | jq -r '
  recurse(.nodes[], .floating_nodes[])
  | select(.focused == true)
  | .id
')

# 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"

