#!/bin/bash

# omarchy:summary=Set the default editor used by omarchy-launch-editor
# omarchy:args=[plain|code|cursor|zed|sublime_text|helix|vim|emacs|nvim]
# omarchy:examples=omarchy default editor | omarchy default editor plain | omarchy default editor helix

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

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

if (($# == 0)); then
  if [[ -f $editor_file ]]; then
    read -r editor <"$editor_file"
  fi

  # sublime-text-4 ships `subl`; older defaults stored `sublime_text`.
  [[ $editor == sublime_text ]] && editor=subl

  [[ -n $editor ]] && echo "$editor" || echo "plain"
  exit 0
fi

case "$1" in
plain) selection="plain"; editor="plain"; name="Plain"; glyph= ;;
code) selection="code"; editor="code"; name="VSCode"; glyph= ;;
cursor) selection="cursor"; editor="cursor"; name="Grok Build"; glyph= ;;
zed | zeditor) selection="zed"; editor="zeditor"; name="Zed"; glyph= ;;
sublime_text | subl) selection="sublime_text"; editor="subl"; name="Sublime Text"; glyph= ;;
helix) selection="helix"; editor="helix"; name="Helix"; glyph= ;;
vim) selection="vim"; editor="vim"; name="Vim"; glyph= ;;
emacs) selection="emacs"; editor="emacs"; name="Emacs"; glyph= ;;
nvim) selection="nvim"; editor="nvim"; name="Neovim"; glyph= ;;
*)
  echo "Usage: omarchy-default-editor <plain|code|cursor|zed|sublime_text|helix|vim|emacs|nvim>"
  exit 1
  ;;
esac

if omarchy-cmd-missing "$editor"; then
  if [[ $installing == "false" ]]; then
    exec omarchy-launch-floating-terminal-with-presentation omarchy-default-editor --install "$selection"
  else
    case "$selection" in
    plain) echo "Installing $name..."; omarchy-pkg-add plain ;;
    code) omarchy-install-editor-vscode ;;
    cursor) echo "Installing $name..."; omarchy-pkg-add cursor-bin ;;
    zed) omarchy-install-editor-zed ;;
    sublime_text) echo "Installing $name..."; omarchy-pkg-add sublime-text-4 ;;
    helix) omarchy-install-editor-helix ;;
    vim) echo "Installing $name..."; omarchy-pkg-add vim ;;
    emacs) omarchy-install-editor-emacs ;;
    nvim) echo "Installing $name..."; omarchy-pkg-add neovim ;;
    esac || exit 1
  fi
fi

mkdir -p "$(dirname "$editor_file")"
printf '%s\n' "$editor" >"$editor_file"

# Files and other apps open a text file with what mimeapps.list names for
# its type, not Omarchy's own default. Point every text type at the editor
# handler, which opens the editor recorded above, so the choice made here is
# the one every app follows.
omarchy-cmd-editor-mimetypes

omarchy-notification-send -g $glyph "$(omarchy-i18n default.editorSet "$name")"
