///|
/// Raised when a text is not a project file that this version can read.
#derive(Eq, Debug)
pub(all) suberror ProjectFileError {
  /// The text is not a project file. The message names what is wrong and, if
  /// it can, the place in the file.
  Damaged(String)
  /// The file has a format that is newer than this version knows. A format above
  /// 2147483647 has the value 2147483647 here.
  NewerFormat(Int32)
}

///|
/// The format that this version writes.
let project_file_format : Int32 = 1

///|
/// The text of `projects.json`, such as
/// `{"format":1,"next":2,"projects":[{"id":1,"path":"/code","added":"5"}]}`.
/// A time is a text, as in the app contract. `opened` is there only for a
/// project that the user opened.
pub fn ProjectList::to_file_text(self : ProjectList) -> String {
  let projects = self.entries
    .iter()
    .map(entry => {
      let fields : Map[String, Json] = {
        "id": entry.id.to_json(),
        "path": Json::string(entry.folder.to_string()),
        "added": entry.added.to_json(),
      }
      if entry.opened is Some(opened) {
        fields["opened"] = opened.to_json()
      }
      Json::object(fields)
    })
    .collect()
  Json::object({
    "format": ToJson::to_json(project_file_format),
    "next": self.next.to_json(),
    "projects": Json::array(projects),
  }).stringify()
}

///|
/// Reads the text of `projects.json`. The paths follow the rules of the
/// platform.
///
/// A format above 1 raises `NewerFormat`, also when the other fields have a form
/// that this version does not know. Each other problem raises `Damaged`: a text
/// that is not JSON, a field that is missing or has a wrong value, a path that
/// is not absolute, a folder or an ID that is there two times, and a next ID
/// that is not above each ID. A field that is not known has no effect.
pub fn ProjectList::of_file_text(
  text : String,
  platform : Platform,
) -> ProjectList raise ProjectFileError {
  let json = @json.parse(text) catch {
    error => raise Damaged("the text is not JSON: \{error}")
  }
  let { format, } : SavedFormat = project_file_part(json)
  guard format <= project_file_format else { raise NewerFormat(format) }
  let { next, projects, } : SavedList = project_file_part(json)
  let entries : Array[Entry] = []
  for i, project in projects {
    let entry = project.entry("/projects/\{i}", platform)
    let id = entry.id.to_int()
    guard !entries.iter().any(other => other.id == entry.id) else {
      raise Damaged("/projects/\{i}/id: the ID \{id} is in the list two times")
    }
    guard !entries.iter().any(other => other.folder.same_folder(entry.folder)) else {
      raise Damaged(
        "/projects/\{i}/path: the folder \"\{entry.folder.to_string()}\" is in the list two times",
      )
    }
    guard next.to_int() > id else {
      raise Damaged(
        "/next: the next ID \{next.to_int()} is not above the ID \{id}",
      )
    }
    entries.push(entry)
  }
  { next, entries: ReadOnlyArray::from_array(entries), }
}

///|
/// Reads the types of the fields. The caller checks the rules between them.
fn[T : @json.FromJson] project_file_part(
  json : Json,
) -> T raise ProjectFileError {
  @json.from_json(json) catch {
    JsonDecodeError((at, message)) =>
      match at.to_string() {
        "" => raise Damaged(message)
        place => raise Damaged("\{place}: \{message}")
      }
  }
}

///|
/// The fields of format 1.
priv struct SavedList {
  next : @app.ProjectId
  projects : Array[SavedProject]
}

///|
impl @json.FromJson for SavedList with fn from_json(json, path) {
  {
    next: project_file_field(json, path, "next"),
    projects: project_file_field(json, path, "projects"),
  }
}

///|
/// A project in the file. Its path is not parsed, because that needs the
/// platform.
priv struct SavedProject {
  id : @app.ProjectId
  path : String
  added : @app.UnixMillis
  opened : @app.UnixMillis?
}

///|
impl @json.FromJson for SavedProject with fn from_json(json, path) {
  {
    id: project_file_field(json, path, "id"),
    path: project_file_field(json, path, "path"),
    added: project_file_field(json, path, "added"),
    opened: project_file_optional_field(json, path, "opened"),
  }
}

///|
fn SavedProject::entry(
  self : SavedProject,
  place : String,
  platform : Platform,
) -> Entry raise ProjectFileError {
  let { id, path, added, opened, } = self
  let folder = FolderPath::FolderPath(path, platform) catch {
    EmptyPath | RelativePath(_) =>
      raise Damaged("\{place}/path: \"\{path}\" is not an absolute path")
  }
  { id, folder, added, opened, }
}

///|
fn[T : @json.FromJson] project_file_field(
  json : Json,
  at : @json.DecodeContext,
  key : String,
) -> T raise @json.JsonDecodeError {
  match project_file_optional_field(json, at, key) {
    Some(value) => value
    None => raise at.error("the field \"\{key}\" is missing")
  }
}

///|
/// Reads a field of a JSON object. The field can be absent or null.
fn[T : @json.FromJson] project_file_optional_field(
  json : Json,
  at : @json.DecodeContext,
  key : String,
) -> T? raise @json.JsonDecodeError {
  guard json is Object(fields) else { raise at.error("expected an object") }
  match fields.get(key) {
    None | Some(Null) => None
    Some(value) => Some(@json.from_json(value, path=at.add_key(key)))
  }
}

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

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