// The shortcuts of the UI. They are for the complete page, also when a text field has the
// focus.

///|
/// A shortcut of the page.
#derive(Eq, Debug)
pub(all) enum Shortcut {
  /// Ctrl+K or Ctrl+Shift+P, and on macOS Cmd+K or Cmd+Shift+P.
  OpenPalette
  /// Ctrl+B, and on macOS Cmd+B. It hides the primary sidebar, or shows it.
  ChangePrimarySidebar
}

///|
pub extend Shortcut with Eq::{equal, not_equal}

///|
pub extend Shortcut with @debug.Debug::{to_repr}

///|
/// The shortcut of a key press, if it has one. `composing` is true for a key of an input
/// method. `alt` is necessary because AltGr is Ctrl+Alt on Windows, and AltGr+K types a
/// character on some keyboards.
///
/// `code` is the key on the keyboard. It counts only when the character is not one of
/// ASCII, because a keyboard for a different alphabet has no K, no P and no B.
pub fn Shortcut::of_key(
  key~ : String,
  code~ : String,
  ctrl~ : Bool,
  alt~ : Bool,
  meta~ : Bool,
  shift~ : Bool,
  composing~ : Bool,
  mac~ : Bool,
) -> Shortcut? {
  let (command, other) = if mac { (meta, ctrl) } else { (ctrl, meta) }
  guard command && !other && !alt && !composing else { None }
  // Caps Lock and Shift give an upper case letter.
  match (key, code) {
    ("k" | "K", _) if !shift => Some(OpenPalette)
    ("p" | "P", _) if shift => Some(OpenPalette)
    ("b" | "B", _) if !shift => Some(ChangePrimarySidebar)
    (_, "KeyK") if !shift && types_no_ascii(key) => Some(OpenPalette)
    (_, "KeyP") if shift && types_no_ascii(key) => Some(OpenPalette)
    (_, "KeyB") if !shift && types_no_ascii(key) => Some(ChangePrimarySidebar)
    _ => None
  }
}

///|
/// The key types a character that is not in ASCII. The name of a key that types
/// nothing, such as `Enter`, has only characters of ASCII.
fn types_no_ascii(key : String) -> Bool {
  key.iter().all(char => char > '\u{7f}')
}

///|
/// The keys of the shortcut, for the user. A shortcut with two forms gives the first.
fn Shortcut::text(self : Shortcut, mac~ : Bool) -> String {
  match (self, mac) {
    (OpenPalette, false) => "Ctrl+K"
    (OpenPalette, true) => "⌘K"
    (ChangePrimarySidebar, false) => "Ctrl+B"
    (ChangePrimarySidebar, true) => "⌘B"
  }
}

///|
/// All forms of the shortcut, for the attribute `aria-keyshortcuts`.
fn Shortcut::aria(self : Shortcut, mac~ : Bool) -> String {
  match (self, mac) {
    (OpenPalette, false) => "Control+K Control+Shift+P"
    (OpenPalette, true) => "Meta+K Meta+Shift+P"
    (ChangePrimarySidebar, false) => "Control+B"
    (ChangePrimarySidebar, true) => "Meta+B"
  }
}

///|
/// The shortcut at the end of a control. A screen reader gets it from
/// `aria-keyshortcuts`.
fn shortcut_hint(shortcut : Shortcut, mac~ : Bool) -> @html.Html {
  @rui.kbd(
    style=["margin-inline-start:auto"],
    attrs=@html.Attrs::build().aria_hidden("true"),
    shortcut.text(mac~),
  )
}

///|
/// The message for a shortcut, or `None` when it does nothing now. The shortcut of the
/// primary sidebar sends the same message as its control. It does nothing while a dialog
/// is open, also the palette, and in a small window.
fn Model::shortcut_msg(self : Model, shortcut : Shortcut) -> Msg? {
  match shortcut {
    OpenPalette => Some(PaletteOpened)
    ChangePrimarySidebar => {
      let action = SetPrimarySidebar(self.primary_sidebar.other())
      guard self.dialog is NoDialog && action.enabled(self) else { None }
      Some(ActionChosen(action))
    }
  }
}

///|
priv suberror ShortcutKeys {
  ShortcutKeys((Shortcut) -> @cmd.Cmd)
}

///|
/// Sends the command of a shortcut when the user presses it, also when a text field has
/// the focus or no element has it. The browser then does not use the shortcut for
/// itself, also when the shortcut does nothing now. A key that stays down counts one
/// time. `@sub.on_key_down` cannot do this, because it does not give the event.
fn on_shortcuts(command : (Shortcut) -> @cmd.Cmd, mac~ : Bool) -> @sub.Sub {
  @sub.custom_sub(
    "shortcuts",
    Local,
    ShortcutKeys(command),
    SubLoader((payload, scheduler) => {
      guard payload is ShortcutKeys(command) else { None }
      let current = Ref(command)
      let target = @dom.document().as_event_target()
      let listener : @dom.Listener = event => {
        if event.to_keyboard_event() is Some(event) &&
          Shortcut::of_key(
            key=event.key(),
            code=event.code(),
            ctrl=event.ctrl_key(),
            alt=event.alt_key(),
            meta=event.meta_key(),
            shift=event.shift_key(),
            composing=event.is_composing(),
            mac~,
          )
          is Some(shortcut) {
          event.prevent_default()
          if !event.repeat() {
            scheduler.add((current.val)(shortcut))
          }
        }
      }
      target.add_event_listener("keydown", listener)
      Some({
        unload: _ => target.remove_event_listener("keydown", listener),
        update_tagger: payload => {
          if payload is ShortcutKeys(command) {
            current.val = command
          }
        },
      })
    }),
  )
}