#!/usr/bin/env bash

# omarchy:summary=Launch the default editor selected via Omarchy defaults.
# omarchy:args=[--inline] <path>

default_editor="$HOME/.local/state/omarchy/defaults/editor"

if [[ ${1:-} == "--inline" ]]; then
  inline=true
  shift
else
  inline=false
fi

if [[ -f $default_editor ]]; then
  read -r editor <"$default_editor"
else
  editor=""
fi

# The chosen editor, then Omarchy's nvim, then whichever editor the distribution installed: a
# Debian image can ship vim or gnome-text-editor and no nvim.
for candidate in "$editor" nvim vim nano micro gnome-text-editor gedit kate mousepad; do
  [[ -n $candidate ]] && omarchy-cmd-present "$candidate" && break
  candidate=""
done
editor="$candidate"

if [[ -z $editor ]]; then
  omarchy-notification-send -u critical "No editor installed" "Install one, or pick one with omarchy-default-editor."
  exit 1
fi

case "${editor##*/}" in
nvim | vim | nano | micro | hx | helix | fresh)
  if [[ $inline == "true" ]]; then
    exec "$editor" "$@"
  else
    exec omarchy-launch-tui "$editor" "$@"
  fi
  ;;
*)
  exec setsid uwsm-app -- "$editor" "$@"
  ;;
esac
