///|
/// Raised when no project in the list has the ID.
#derive(Eq, Debug)
pub suberror UnknownProject {
  UnknownProject(@app.ProjectId)
}

///|
/// A folder in a project list.
#derive(Eq, Debug)
pub struct Entry {
  id : @app.ProjectId
  folder : FolderPath
  /// The time when the user added the project.
  added : @app.UnixMillis
  /// The time when the user opened the project last, if the user opened it.
  opened : @app.UnixMillis?
}

///|
/// The projects of an instance, in the order in which the user added them.
///
/// A folder is in the list one time, and an ID is for one project only, also
/// after the project is removed. A list does not change: each operation gives a
/// new list. `==` compares the paths as `FolderPath` does.
#derive(Eq, Debug)
struct ProjectList {
  /// The ID of the next new project. It is above each ID that was used.
  next : @app.ProjectId
  entries : ReadOnlyArray[Entry]
}

///|
/// The largest number that an ID or a format can be.
let project_largest_int : Int32 = 2147483647

///|
/// An ID that is valid by construction.
fn project_id_of_valid(value : Int32) -> @app.ProjectId {
  @app.ProjectId::ProjectId(value) catch {
    BelowOne(value) => abort("the project ID \{value} is less than 1")
  }
}

///|
/// The list without projects. The first project gets the ID 1.
pub fn ProjectList::empty() -> ProjectList {
  { next: project_id_of_valid(1), entries: [], }
}

///|
/// Adds a folder at the end of the list, and gives its entry. The new project is
/// not opened. When the folder is in the list, the result is `AlreadyListed`,
/// the same list and the entry that is there. `open` sets the time of the last
/// open.
///
/// The function stops the program with `abort` when the next ID of the list is
/// the largest one, 2147483647, and the folder is new. The list then cannot have
/// a next ID above each ID that was used. Only a project file that a person
/// edited can have such an ID.
pub fn ProjectList::add(
  self : ProjectList,
  folder : FolderPath,
  now : @app.UnixMillis,
) -> (ProjectList, Entry, @app.Addition) {
  if self.entries.iter().find_first(entry => entry.folder.same_folder(folder))
    is Some(entry) {
    return (self, entry, AlreadyListed)
  }
  let entry = { id: self.next, folder, added: now, opened: None, }
  guard self.next.to_int() < project_largest_int else {
    abort(
      "the project list has no free ID after \{project_largest_int}; correct \"next\" in the project file",
    )
  }
  let next = project_id_of_valid(self.next.to_int() + 1)
  let entries = ReadOnlyArray::from_array([..self.entries, entry])
  ({ next, entries, }, entry, New)
}

///|
fn ProjectList::entry(
  self : ProjectList,
  id : @app.ProjectId,
) -> Entry raise UnknownProject {
  match self.entries.iter().find_first(entry => entry.id == id) {
    Some(entry) => entry
    None => raise UnknownProject(id)
  }
}

///|
/// Sets the time of the last open of a project, and gives its new entry. The
/// order of the list does not change.
pub fn ProjectList::open(
  self : ProjectList,
  id : @app.ProjectId,
  now : @app.UnixMillis,
) -> (ProjectList, Entry) raise UnknownProject {
  let opened = { ..self.entry(id), opened: Some(now), }
  let entries = self.entries.map(entry => {
    if entry.id == id {
      opened
    } else {
      entry
    }
  })
  ({ ..self, entries, }, opened)
}

///|
/// Removes a project from the list, and gives the entry that it had. The list
/// does not use its ID again.
pub fn ProjectList::remove(
  self : ProjectList,
  id : @app.ProjectId,
) -> (ProjectList, Entry) raise UnknownProject {
  let removed = self.entry(id)
  ({ ..self, entries: self.entries.filter(entry => entry.id != id), }, removed)
}

///|
/// The entries, in the order in which the user added them.
pub fn ProjectList::entries(self : ProjectList) -> ReadOnlyArray[Entry] {
  self.entries
}

///|
/// True when the name of the folder is equal to the text. Windows ignores the
/// case of letters.
fn FolderPath::is_named(self : FolderPath, name : String) -> Bool {
  self.key(self.name()) == self.key(name)
}

///|
/// The details of each project, in the order of the list. `state_of` says
/// whether the folder of an entry exists.
///
/// A project has a `parent` while another project has the same name, by the rule
/// of the platform. The parents are there also when they are equal too.
pub fn ProjectList::describe(
  self : ProjectList,
  state_of : (Entry) -> @app.FolderState,
) -> Array[@app.Project] {
  let projects = []
  for entry in self.entries {
    let name = entry.folder.name()
    let shared = self.entries
      .iter()
      .any(other => other.id != entry.id && other.folder.is_named(name))
    let project : @app.Project = {
      id: entry.id,
      name,
      parent: if shared {
        entry.folder.parent_name()
      } else {
        None
      },
      path: entry.folder.to_string(),
      folder: state_of(entry),
      added: entry.added,
      opened: entry.opened,
    }
    projects.push(project)
  }
  projects
}

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

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

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

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

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

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