// What a user can do in the UI. The controls on the screen, the command palette and
// `step` use this one list (design UI-2).

///|
/// An operation of the user.
#derive(Eq, Debug)
pub(all) enum Action {
  OpenProject(@app.Project)
  /// Switches to a peer workspace of an open project.
  OpenWorkspace(@app.Project, @app.Workspace)
  /// Opens the dialog that asks for the path.
  AddProject
  RemoveProject(@app.Project)
  /// Switches the active workspace perspective.
  SetPerspective(Perspective)
  /// Moves one step backward in shell navigation history.
  NavigateBack
  /// Moves one step forward in shell navigation history.
  NavigateForward
  /// Opens the full-page Settings overlay.
  OpenSettings
  /// Gives the primary sidebar this state.
  SetPrimarySidebar(PrimarySidebar)
  /// Opens the dialog that asks before the stop.
  StopApp
}

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

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

///|
/// What an action is, without the details that can change. Two projects can have the
/// same name, and a project can get a different place in the list.
#derive(Eq, Debug)
pub(all) enum ActionId {
  OpenId(@app.ProjectId)
  OpenWorkspaceId(@app.ProjectId, @app.WorkspaceId)
  AddId
  RemoveId(@app.ProjectId)
  PerspectiveId(Perspective)
  NavigateBackId
  NavigateForwardId
  SettingsId
  PrimarySidebarId
  StopId
}

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

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

///|
pub fn Action::id(self : Action) -> ActionId {
  match self {
    OpenProject(project) => OpenId(project.id)
    OpenWorkspace(project, workspace) =>
      OpenWorkspaceId(project.id, workspace.id)
    AddProject => AddId
    RemoveProject(project) => RemoveId(project.id)
    SetPerspective(perspective) => PerspectiveId(perspective)
    NavigateBack => NavigateBackId
    NavigateForward => NavigateForwardId
    OpenSettings => SettingsId
    SetPrimarySidebar(_) => PrimarySidebarId
    StopApp => StopId
  }
}

///|
/// What stays the same while an action is the same one, as the key of its element in
/// the page. A different action then gets a new element, also at the same place. If
/// that occurs between the press and the release of a button, then the browser gives no
/// click.
fn ActionId::key(self : ActionId) -> String {
  match self {
    OpenId(project) => "open-\{project.short_id()}"
    OpenWorkspaceId(project, workspace) =>
      "open-ws-\{project.short_id()}-\{workspace.short_id()}"
    AddId => "add"
    RemoveId(project) => "remove-\{project.short_id()}"
    PerspectiveId(Plan) => "perspective-plan"
    PerspectiveId(Build) => "perspective-build"
    PerspectiveId(Review) => "perspective-review"
    PerspectiveId(Knowledge) => "perspective-knowledge"
    NavigateBackId => "nav-back"
    NavigateForwardId => "nav-forward"
    SettingsId => "settings"
    PrimarySidebarId => "primary-sidebar"
    StopId => "stop"
  }
}

///|
/// The user sees the same actions in both lists. The server changes the time when a
/// project or workspace opens, but the page does not show it and no action uses it.
fn look_same(
  one : ReadOnlyArray[Action],
  other : ReadOnlyArray[Action],
) -> Bool {
  let shown = (action : Action) => {
    match action {
      OpenProject(project) => OpenProject({ ..project, opened: None, })
      OpenWorkspace(project, workspace) =>
        OpenWorkspace({ ..project, opened: None, }, {
          ..workspace,
          opened: None,
        })
      RemoveProject(project) => RemoveProject({ ..project, opened: None, })
      AddProject
      | SetPerspective(_)
      | NavigateBack
      | NavigateForward
      | OpenSettings
      | SetPrimarySidebar(_)
      | StopApp => action
    }
  }
  one.map(shown) == other.map(shown)
}

///|
/// A group of actions in the command palette.
#derive(Eq, Debug)
pub(all) enum ActionGroup {
  Projects
  Workspaces
  Commands
}

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

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

///|
/// Short display label for a workspace checkout position.
pub fn workspace_position_label(position : @app.Position) -> String {
  match position {
    Unversioned => "folder"
    Unborn(line~) => "\{line} (unborn)"
    OnLine(line~, ..) => line.to_string()
    Detached(revision~) => "detached \{revision.short()}"
  }
}

///|
/// The actions of a view, also the ones that are disabled now: each project in the
/// order of the list (with peer workspaces of an open multi-workspace project), and then
/// the commands. A small window has no primary sidebar.
pub fn actions(model : Model) -> ReadOnlyArray[Action] {
  let commands : Array[Action] = [AddProject]
  let workspace_actions : Array[Action] = []
  if model.open_project() is Some(project) {
    commands.push(RemoveProject(project))
    if model.has_perspectives() {
      commands.push(SetPerspective(Plan))
      commands.push(SetPerspective(Build))
      commands.push(SetPerspective(Review))
      commands.push(SetPerspective(Knowledge))
    }
    if model.open_workspaces() is Some(Ready(Populated(set))) &&
      set.length() > 1 {
      for ws in set.workspaces() {
        workspace_actions.push(OpenWorkspace(project, ws))
      }
    }
  }
  commands.push(NavigateBack)
  commands.push(NavigateForward)
  commands.push(OpenSettings)
  if model.window is Wide {
    commands.push(SetPrimarySidebar(model.primary_sidebar.other()))
  }
  commands.push(StopApp)
  let projects = model.projects.unwrap_or([])
  ReadOnlyArray::from_array(
    [
      ..projects.iter().map(project => OpenProject(project)),
      ..workspace_actions,
      ..commands,
    ],
  )
}

///|
/// The text of the action for the user.
pub fn Action::title(self : Action) -> String {
  match self {
    OpenProject(project) => project.title.to_string()
    OpenWorkspace(_, workspace) => workspace.name.to_string()
    AddProject => "Add project…"
    RemoveProject(_) => "Remove project from list"
    SetPerspective(Plan) => "Switch to Plan"
    SetPerspective(Build) => "Switch to Build"
    SetPerspective(Review) => "Switch to Review"
    SetPerspective(Knowledge) => "Switch to Knowledge"
    NavigateBack => "Navigate Back"
    NavigateForward => "Navigate Forward"
    OpenSettings => "Open Settings"
    SetPrimarySidebar(Hidden) => "Hide primary sidebar"
    SetPrimarySidebar(Shown) => "Show primary sidebar"
    StopApp => "Stop Mission Control"
  }
}

///|
pub fn Action::group(self : Action) -> ActionGroup {
  match self {
    OpenProject(_) => Projects
    OpenWorkspace(_, _) => Workspaces
    AddProject
    | RemoveProject(_)
    | SetPerspective(_)
    | NavigateBack
    | NavigateForward
    | OpenSettings
    | SetPrimarySidebar(_)
    | StopApp => Commands
  }
}

///|
/// Words that find the action in the command palette, and that its title does not have.
pub fn Action::search_words(self : Action) -> Array[String] {
  match self {
    OpenProject(project) => {
      let words = [project.name, project.path, project.id.short_id()]
      if project.caption is Some(caption) {
        words.push(caption.to_string())
      }
      words
    }
    OpenWorkspace(project, workspace) =>
      [
        "workspace",
        project.title.to_string(),
        workspace.path,
        workspace_position_label(workspace.position),
        workspace.id.short_id(),
      ]
    AddProject => ["create", "new", "folder"]
    RemoveProject(project) =>
      [
        "delete",
        "forget",
        project.title.to_string(),
        project.name,
        project.path,
      ]
    SetPerspective(Plan) =>
      ["zen", "board", "kanban", "workflow", "perspective"]
    SetPerspective(Build) => ["linear", "pipeline", "delivery", "perspective"]
    SetPerspective(Review) =>
      ["read", "reader", "editorial", "docs", "perspective"]
    SetPerspective(Knowledge) =>
      [
        "dictionary", "rdf", "skos", "knowledge", "kb", "ontology", "perspective",
      ]
    NavigateBack => ["history", "previous", "back"]
    NavigateForward => ["history", "next", "forward"]
    OpenSettings => ["preferences", "workflow", "studio", "theme", "appearance"]
    SetPrimarySidebar(_) =>
      ["toggle", "collapse", "expand", "panel", "side bar"]
    StopApp => ["quit", "exit", "close"]
  }
}

///|
/// The user can do the action now. `step` ignores an action that is not enabled.
pub fn Action::enabled(self : Action, model : Model) -> Bool {
  match self {
    // The page has the list, so it can open a project or workspace by itself.
    OpenProject(_) | OpenWorkspace(_, _) => true
    SetPerspective(_) => model.has_perspectives()
    NavigateBack => model.history.can_go_back()
    NavigateForward => model.history.can_go_forward()
    OpenSettings => true
    SetPrimarySidebar(_) => model.window is Wide
    AddProject | RemoveProject(_) | StopApp => model.connection is Connected
  }
}

///|
/// The action has each word of the query in its title or in one of its search words.
/// The order of the words and their case make no difference.
pub fn finds(query : String, title : String, words : Array[String]) -> Bool {
  let texts = [title, ..words].map(lower_case)
  words_of(lower_case(query))
  .iter()
  .all(word => texts.iter().any(text => text.contains(word)))
}

///|
/// The text in lower case. `String::to_lower` changes only the letters A to Z.
extern "js" fn lower_case(text : String) -> String =
  #| (text) => text.toLowerCase()

///|
/// The words of a text, which each kind of space separates.
extern "js" fn words_of(text : String) -> FixedArray[String] =
  #| (text) => text.split(/\s+/).filter(word => word !== "")