///|
/// The name of the file with the version of an installed app and its engine.
pub let app_record_file : String = "mission-control-app.json"

///|
/// Raised when the text of `mission-control-app.json` is wrong. An installation then
/// replaces the app completely.
#derive(Eq, Debug)
pub(all) suberror AppRecordError {
  InvalidAppRecord
  /// The path of an engine file leads out of the folder of the app.
  InvalidEnginePath(String)
}

///|
/// The path of a file of the engine, from the folder of the app and with `/` between its
/// names.
#derive(Eq, Debug)
struct EnginePath {
  text : String
}

///|
/// A path has names that are not empty, `.` or `..`. A name has no backslash and no colon,
/// because these have a meaning on Windows.
pub fn EnginePath::EnginePath(text : String) -> EnginePath raise AppRecordError {
  guard text.split("/").all(name => !(name is ("" | "." | ".."))) &&
    text.iter().all(c => !(c is ('\\' | ':' | '\u{0}'..<='\u{1f}'))) else {
    raise InvalidEnginePath(text)
  }
  { text, }
}

///|
pub fn EnginePath::to_string(self : EnginePath) -> String {
  self.text
}

///|
/// The engine of an installed app.
#derive(Eq, Debug)
struct InstalledEngine {
  id : EngineId
  paths : ReadOnlyArray[EnginePath]
  size : UInt64
}

///|
/// `size` is the number of bytes of all files in the paths. An installation uses the engine
/// again only when it still has this size. On Linux there are no paths, because the apps
/// share the folder of the engine.
pub fn InstalledEngine::InstalledEngine(
  id : EngineId,
  paths : ArrayView[EnginePath],
  size~ : UInt64,
) -> InstalledEngine {
  { id, paths: ReadOnlyArray::from_iter(paths.iter()), size, }
}

///|
/// The number of bytes of the engine files.
pub fn InstalledEngine::size(self : InstalledEngine) -> UInt64 {
  self.size
}

///|
pub fn InstalledEngine::id(self : InstalledEngine) -> EngineId {
  self.id
}

///|
/// The files of the engine in the folder of the app.
pub fn InstalledEngine::paths(
  self : InstalledEngine,
) -> ReadOnlyArray[EnginePath] {
  self.paths
}

///|
/// What an installation knows about the app that it installed. It is the content of
/// `mission-control-app.json`.
#derive(Eq, Debug)
pub(all) struct AppRecord {
  version : @contracts.Version
  engine : InstalledEngine
}

///|
/// Reads the text of `mission-control-app.json`.
pub fn AppRecord::parse(text : String) -> AppRecord raise AppRecordError {
  let json = @json.parse(text) catch { _ => raise InvalidAppRecord }
  guard json
    is {
      "format": Number(1.0, ..),
      "version": String(version),
      "engine": {
        "id": String(id),
        "paths": Array(paths),
        "size": Number(size, ..),
        ..
      },
      ..
    } else {
    raise InvalidAppRecord
  }
  let version = @contracts.Version::Version(version) catch {
    _ => raise InvalidAppRecord
  }
  let id = EngineId(id) catch { _ => raise InvalidAppRecord }
  // A number in JSON is exact up to 2^53.
  guard size >= 0 && size <= 9007199254740992 && size.floor() == size else {
    raise InvalidAppRecord
  }
  let engine_paths = []
  for path in paths {
    guard path is String(text) else { raise InvalidAppRecord }
    engine_paths.push(EnginePath(text))
  }
  { version, engine: InstalledEngine(id, engine_paths, size=size.to_uint64()), }
}

///|
pub impl ToJson for AppRecord with fn to_json(self) {
  {
    "format": 1,
    "version": self.version.to_json(),
    "engine": {
      "id": self.engine.id.text,
      "paths": Json::array(
        self.engine.paths.iter().map(path => Json::string(path.text)).collect(),
      ),
      "size": Json::number(self.engine.size.to_double()),
    },
  }
}

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

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

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

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

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

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

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

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

///|
pub extend AppRecord with ToJson::{to_json}