#!/usr/bin/env bash

echo "-- initiate -- "
date
echo ""

tui_name=$1
active_popup=$(hyprctl clients -j | jq -r '.[] | select(.class | startswith("org.hakase.")) | .class')

if [[ -z ${tui_name} ]]; then
  echo "Usage: $(basename "$0") [tui-name]"
  exit 1
fi

popup_checker() {
  if [[ -z "$active_popup" ]]; then
    echo "no_popup"
  elif [[ "$active_popup" != "org.hakase.popup.${tui_name}" ]]; then
    echo "different"
  else
    echo "same"
  fi
}

launch() {
  echo "[LOG: $(date)]"
  exec setsid uwsm-app -- xdg-terminal-exec --app-id=org.hakase.popup."${tui_name}" -e "${tui_name}"
}

focus() {
  exec hyprctl dispatch focuswindow "class:org.hakase.popup.${tui_name}"
}

replace() {
  hyprctl dispatch closewindow "class:${active_popup}"
  sleep 1
  launch
}

run() {
  local status
  status=$(popup_checker)

  if [[ "$status" == "no_popup" ]]; then
    echo "[LOG: $(date)] no popup, launching..."
    launch
  elif [[ "$status" == "same" ]]; then
    echo "[LOG: $(date)] same popup, focusing..."
    focus
  elif [[ "$status" == "different" ]]; then
    echo "[LOG: $(date)] different popup, closing and relaunching..."
    replace
  fi
}

run
