// The shortcuts of the UI. They are for the complete page, also when a text field has the
// focus, except plain-key perspective and overlay shortcuts which yield to text fields.

///|
/// 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
  /// Alt+Left moves backward in shell navigation history.
  GoBack
  /// Alt+Right moves forward in shell navigation history.
  GoForward
  /// Plain `1`, `2`, `3`, or `4` switches perspective when no dialog or text field has focus.
  SwitchPerspective(Perspective)
  /// Plain `Escape` dismisses the Settings overlay or floating gate inspector.
  DismissOverlay
}

///|
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. `typing` is true when an input or editable control has focus.
///
/// `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,
  typing~ : Bool = false,
) -> Shortcut? {
  guard !composing else { None }
  let (command, other) = if mac { (meta, ctrl) } else { (ctrl, meta) }
  if command && !other && !alt {
    // Caps Lock and Shift give an upper case letter.
    return 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
    }
  }
  if alt && !ctrl && !meta && !shift && !typing {
    return match key {
      "ArrowLeft" => Some(GoBack)
      "ArrowRight" => Some(GoForward)
      _ => None
    }
  }
  if !ctrl && !alt && !meta && !shift {
    if key == "Escape" {
      return Some(DismissOverlay)
    }
    if !typing {
      return match key {
        "1" => Some(SwitchPerspective(Plan))
        "2" => Some(SwitchPerspective(Build))
        "3" => Some(SwitchPerspective(Review))
        "4" => Some(SwitchPerspective(Knowledge))
        _ => None
      }
    }
  }
  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"
    (GoBack, false) => "Alt+←"
    (GoBack, true) => "⌥←"
    (GoForward, false) => "Alt+→"
    (GoForward, true) => "⌥→"
    (SwitchPerspective(Plan), _) => "1"
    (SwitchPerspective(Build), _) => "2"
    (SwitchPerspective(Review), _) => "3"
    (SwitchPerspective(Knowledge), _) => "4"
    (DismissOverlay, _) => "Esc"
  }
}

///|
/// 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"
    (GoBack, _) => "Alt+ArrowLeft"
    (GoForward, _) => "Alt+ArrowRight"
    (SwitchPerspective(Plan), _) => "1"
    (SwitchPerspective(Build), _) => "2"
    (SwitchPerspective(Review), _) => "3"
    (SwitchPerspective(Knowledge), _) => "4"
    (DismissOverlay, _) => "Escape"
  }
}

///|
/// 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.
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 &&
        self.settings is Closed &&
        action.enabled(self) else {
        None
      }
      Some(ActionChosen(action))
    }
    GoBack => {
      guard self.dialog is NoDialog &&
        self.settings is Closed &&
        NavigateBack.enabled(self) else {
        None
      }
      Some(ActionChosen(NavigateBack))
    }
    GoForward => {
      guard self.dialog is NoDialog &&
        self.settings is Closed &&
        NavigateForward.enabled(self) else {
        None
      }
      Some(ActionChosen(NavigateForward))
    }
    SwitchPerspective(perspective) => {
      guard self.dialog is NoDialog &&
        self.settings is Closed &&
        SetPerspective(perspective).enabled(self) else {
        None
      }
      Some(ActionChosen(SetPerspective(perspective)))
    }
    DismissOverlay =>
      if self.dialog is NoDialog {
        if self.settings is Open(_) {
          Some(CloseSettings)
        } else if self.active_mockup().inspector_open() {
          Some(CloseInspector)
        } else {
          None
        }
      } else {
        None
      }
  }
}

///|
extern "js" fn is_typing_target(event : @dom.KeyboardEvent) -> Bool =
  #| (event) => {
  #|   const el = event.target;
  #|   if (!el || typeof el.tagName !== "string") return false;
  #|   const tag = el.tagName.toUpperCase();
  #|   return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!el.isContentEditable;
  #| }

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

///|
/// Sends the command of a shortcut when the user presses it and the view handles it.
/// Modified shortcuts call `prevent_default()` only when handled. Plain keys (`1`/`2`/`3`/`4`
/// and `Escape`) never call `prevent_default()`, and `Alt+ArrowLeft`/`Alt+ArrowRight`
/// yield to focused text fields.
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~,
            typing=is_typing_target(event),
          )
          is Some(shortcut) &&
          (current.val)(shortcut) is Some(cmd) {
          // Only prevent browser default when the shortcut is handled and modified.
          if !(shortcut is (DismissOverlay | SwitchPerspective(_))) {
            event.prevent_default()
          }
          if !event.repeat() {
            scheduler.add(cmd)
          }
        }
      }
      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
          }
        },
      })
    }),
  )
}