///|
/// What the desktop app does.
#derive(Eq, Debug)
pub(all) enum DesktopCommand {
  /// Opens the window of an instance, or brings it to the front. Without a name, the app
  /// selects the instance. The window opens the project of the folder.
  OpenWindow(instance~ : @app.InstanceName?, folder~ : @core.FolderPath?)
  /// Runs the server of an instance. The app starts itself with this command.
  Serve(@app.InstanceName)
}

///|
/// An option of the desktop app.
#derive(Eq, Debug)
pub(all) enum DesktopOption {
  Instance
  Folder
}

///|
/// Raised when the desktop app cannot use its arguments.
#derive(Eq, Debug)
pub(all) suberror ArgumentError {
  /// The command does not have this argument.
  UnknownArgument(String)
  /// No value comes after the option.
  MissingValue(DesktopOption)
  /// The arguments have the option two times.
  RepeatedOption(DesktopOption)
  /// `serve` comes without the option `--instance`.
  MissingInstance
  WrongInstance(@app.InstanceNameError)
  WrongFolder(@core.FolderPathError)
}

///|
/// The word that selects the command `Serve`.
let serve_word : String = "serve"

///|
/// The text of the option.
pub fn DesktopOption::text(self : DesktopOption) -> String {
  match self {
    Instance => "--instance"
    Folder => "--folder"
  }
}

///|
/// The values of the options that the parser read.
priv struct Values {
  instance : @app.InstanceName?
  folder : @core.FolderPath?
}

///|
/// Reads the arguments after the name of the program:
///
/// - `[--instance NAME] [--folder PATH]` opens the window.
/// - `serve --instance NAME` runs the server.
///
/// `--folder` needs a complete path, because the working directory of an app depends on
/// how the user opens it. The platform gives the rules for the path.
pub fn DesktopCommand::parse(
  args : ArrayView[String],
  platform : @core.Platform,
) -> DesktopCommand raise ArgumentError {
  match args {
    [word, .. options] if word == serve_word => {
      let values = read_options(options, [Instance], platform)
      guard values.instance is Some(instance) else { raise MissingInstance }
      Serve(instance)
    }
    _ => {
      let { instance, folder, } = read_options(
        args,
        [Instance, Folder],
        platform,
      )
      OpenWindow(instance~, folder~)
    }
  }
}

///|
/// Reads the options that a command has.
fn read_options(
  args : ArrayView[String],
  known : ArrayView[DesktopOption],
  platform : @core.Platform,
) -> Values raise ArgumentError {
  for rest = args, values = Values::{ instance: None, folder: None, } {
    guard rest is [text, .. after] else { break values }
    guard known.iter().find_first(option => option.text() == text)
      is Some(option) else {
      raise UnknownArgument(text)
    }
    // A name and a complete path never start with `--`.
    guard after is [value, .. after] && !value.has_prefix("--") else {
      raise MissingValue(option)
    }
    let next = match option {
      Instance => {
        guard values.instance is None else { raise RepeatedOption(option) }
        let name = @app.InstanceName::InstanceName(value) catch {
          error => raise WrongInstance(error)
        }
        { ..values, instance: Some(name), }
      }
      Folder => {
        guard values.folder is None else { raise RepeatedOption(option) }
        let path = @core.FolderPath::FolderPath(value, platform) catch {
          error => raise WrongFolder(error)
        }
        { ..values, folder: Some(path), }
      }
    }
    continue after, next
  }
}

///|
/// The arguments that give this command.
pub fn DesktopCommand::to_arguments(
  self : DesktopCommand,
) -> ReadOnlyArray[String] {
  match self {
    Serve(name) => [serve_word, Instance.text(), name.to_string()]
    OpenWindow(instance~, folder~) => {
      let args = []
      if instance is Some(name) {
        args.append([DesktopOption::Instance.text(), name.to_string()])
      }
      if folder is Some(path) {
        args.append([DesktopOption::Folder.text(), path.to_string()])
      }
      ReadOnlyArray::from_array(args)
    }
  }
}

///|
/// The problem, as text for people.
pub fn ArgumentError::message(self : ArgumentError) -> String {
  match self {
    UnknownArgument(text) =>
      "The desktop app does not know the argument '\{text}'."
    MissingValue(option) => "The option \{option.text()} needs a value."
    RepeatedOption(option) => "Use the option \{option.text()} only one time."
    MissingInstance => "The command serve needs the option --instance."
    WrongInstance(error) =>
      "The option --instance has a wrong value. \{name_problem(error)}"
    WrongFolder(EmptyPath) => "The option --folder has an empty value."
    WrongFolder(RelativePath(text)) =>
      "The option --folder has the value '\{text}', which is not a complete path."
  }
}

///|
/// The problem with an instance name, as text for people.
fn name_problem(error : @app.InstanceNameError) -> String {
  let InvalidInstanceName(text~, ..) = error
  "'\{text}' is not the name of an instance. A name has 1 to 32 lower-case letters, digits and hyphens, and starts with a letter."
}

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

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

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

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

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

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