///|
/// The folder of a project that the server gave. `None` when its path is not an
/// absolute path on the platform.
fn project_folder(project : @app.Project, platform : Platform) -> FolderPath? {
  Some(FolderPath::FolderPath(project.path, platform)) catch {
    EmptyPath | RelativePath(_) => None
  }
}

///|
/// The nearest project that contains the folder: the project folder that is the
/// deepest one. A project whose path does not parse on the platform of the
/// folder is ignored.
pub fn nearest_project(
  projects : ArrayView[@app.Project],
  current : FolderPath,
) -> @app.Project? {
  let mut nearest : (@app.Project, FolderPath)? = None
  for project in projects {
    guard project_folder(project, current.platform) is Some(folder) &&
      folder.contains(current) else {
      continue
    }
    // When two folders contain the current folder, one of them contains the
    // other one. The inner one is nearer.
    if nearest is Some((_, best)) && !best.contains(folder) {
      continue
    }
    nearest = Some((project, folder))
  }
  nearest.map(found => found.0)
}

///|
/// The project that the user opened last. For equal times it is the later one in
/// the list. `None` when the user opened no project.
pub fn last_opened(projects : ArrayView[@app.Project]) -> @app.Project? {
  let mut last : (@app.Project, Int64)? = None
  for project in projects {
    guard project.opened is Some(opened) else { continue }
    let time = opened.to_int64()
    if last is Some((_, latest)) && time < latest {
      continue
    }
    last = Some((project, time))
  }
  last.map(found => found.0)
}

///|
/// How a person names a project on the command line.
///
/// `find` compares a name with the rule of the path of each project: it ignores
/// the case of letters for a project with a Windows path, and compares the exact
/// text for each other project.
#derive(Eq, Debug)
pub(all) enum ProjectRef {
  ById(@app.ProjectId)
  ByPath(FolderPath)
  /// The name of the folder. A name is any text and has no rules here.
  ByName(String)
}

///|
/// Raised when a text does not select one project.
#derive(Eq, Debug)
pub(all) suberror ProjectRefError {
  /// No project has this ID, path or name.
  NoMatch(String)
  /// More than one project has this name. The projects are in the order of the
  /// list.
  Ambiguous(String, ReadOnlyArray[@app.Project])
  /// The text is empty, is a number that is not an ID, or has a separator and
  /// is not a path.
  InvalidRef(String)
}

///|
/// Reads the text that a person gives for a project.
///
/// - A text of only the digits `0` to `9` is an ID.
/// - A text that is `.` or `..`, or that has a separator of the platform, is a
///   path. A relative path starts at the current folder. An absolute path
///   always has a separator.
/// - Each other text is a name.
///
/// A folder can have a name of only digits, such as `2026`. The text `2026` is
/// then an ID and not this name. Use `./2026` or the ID of the project.
pub fn ProjectRef::ProjectRef(
  text : String,
  current : FolderPath,
) -> ProjectRef raise ProjectRefError {
  guard text != "" else { raise InvalidRef(text) }
  if text.iter().all(c => c is ('0'..<='9')) {
    let id = @app.ProjectId::ProjectId(@string.parse_int(text, radix=10)) catch {
      _ => raise InvalidRef(text)
    }
    ById(id)
  } else if text == "." ||
    text == ".." ||
    text.iter().any(c => is_separator(c, current.platform)) {
    let folder = FolderPath::resolve(text, current) catch {
      EmptyPath | RelativePath(_) => raise InvalidRef(text)
    }
    ByPath(folder)
  } else {
    ByName(text)
  }
}

///|
/// Finds the project in the list. `NoMatch` names the ID, the complete path or
/// the name. The folder of the project can be missing on the disk.
///
/// Names follow the rule of the platform: Windows ignores the case of letters.
/// The path of a project tells the platform, because the list and the current
/// folder are on one machine. A project whose path does not parse is ignored,
/// except when the reference is an ID.
pub fn ProjectRef::find(
  self : ProjectRef,
  projects : ArrayView[@app.Project],
) -> @app.Project raise ProjectRefError {
  let (text, matches) = match self {
    ById(id) =>
      (id.to_int().to_string(), projects.filter(project => project.id == id))
    ByPath(folder) =>
      (
        folder.to_string(),
        projects.filter(project => {
          project_folder(project, folder.platform) is Some(other) &&
          other.same_folder(folder)
        }),
      )
    ByName(name) =>
      (name, projects.filter(project => project_has_name(project, name)))
  }
  match matches {
    [] => raise NoMatch(text)
    [project] => project
    _ => raise Ambiguous(text, ReadOnlyArray::from_array(matches))
  }
}

///|
/// True when the folder of the project has the name. A clean path is absolute on
/// Windows or on the other platforms, and never on both. Linux and macOS have
/// the same rules.
fn project_has_name(project : @app.Project, name : String) -> Bool {
  let folder = match project_folder(project, Linux) {
    None => project_folder(project, Windows)
    found => found
  }
  folder is Some(folder) && folder.is_named(name)
}

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

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

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

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