#!/bin/bash

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

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

# --inline waits for the editor; --terminal also keeps it in the calling
# terminal, so a window editor gives way to vi.
inline=false
terminal=false
case ${1:-} in
--inline) inline=true && shift ;;
--terminal) inline=true && terminal=true && shift ;;
esac

terminal_editors="nvim vim vi nano micro hx helix fresh"

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

# sublime-text-4 ships `subl` on PATH, not `sublime_text`.
[[ $editor == sublime_text ]] && editor=subl

omarchy-cmd-present "$editor" || editor="nvim"

# A window editor can't open in a terminal, nor in a session without a display
# (SSH, a TTY), so those edit in vi, which works everywhere.
if [[ $terminal == "true" || -z ${WAYLAND_DISPLAY:-} ]] && [[ " $terminal_editors " != *" ${editor##*/} "* ]]; then
  editor="vi"
fi

case "${editor##*/}" in
plain)
  # Plain runs until its window closes, so $EDITOR (git commit, sudoedit)
  # waits for it inline.
  if [[ $inline == "true" ]]; then
    exec "$editor" -- "$@"
  else
    exec setsid uwsm-app -- "$editor" -- "$@"
  fi
  ;;
nvim | vim | vi | nano | micro | hx | helix | fresh)
  if [[ $inline == "true" ]]; then
    exec "$editor" -- "$@"
  else
    exec omarchy-launch-tui "$editor" -- "$@"
  fi
  ;;
*)
  exec setsid uwsm-app -- "$editor" -- "$@"
  ;;
esac
