///|
/// Raised when a text is not a part of a release.
#derive(Eq, Debug)
pub(all) suberror ReleaseError {
  /// The list has a format that this version does not know.
  NewerFormat(Int32)
  /// The text of the list is wrong. The text says which part, for people.
  WrongList(String)
  /// A name of a file has a separator or another character that is not allowed.
  InvalidFileName(String)
  /// A size is not a whole number from 1 to 4 GB.
  InvalidSize(Double)
  /// A text is not a SHA-256 in 64 lower-case hexadecimal digits.
  InvalidSha256(String)
  /// The ID of an engine has a character that is not allowed in the name of a folder.
  InvalidEngineId(String)
}

///|
/// The name of the file with the list of a release.
pub let release_list_file : String = "desktop.json"

///|
/// The format of the list that this version writes, and the newest one that it reads.
let list_format : Int32 = 1

///|
/// The name of one file, without a folder. So a list cannot select a path.
#derive(Eq, Hash, Debug)
struct FileName {
  text : String
}

///|
/// A name has 1 to 120 letters, digits, periods, hyphens and underscores. It starts with a
/// letter or a digit.
pub fn FileName::FileName(text : String) -> FileName raise ReleaseError {
  guard text.length() <= 120 &&
    text is ['a'..<='z' | 'A'..<='Z' | '0'..<='9', ..] &&
    text
    .iter()
    .all(c => c is ('a'..<='z' | 'A'..<='Z' | '0'..<='9' | '.' | '-' | '_')) else {
    raise InvalidFileName(text)
  }
  { text, }
}

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

///|
/// The SHA-256 of a file.
#derive(Eq, Hash, Debug)
struct Sha256 {
  text : String
}

///|
/// Reads 64 lower-case hexadecimal digits.
pub fn Sha256::Sha256(text : String) -> Sha256 raise ReleaseError {
  guard text.length() == 64 &&
    text.iter().all(c => c is ('0'..<='9' | 'a'..<='f')) else {
    raise InvalidSha256(text)
  }
  { text, }
}

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

///|
/// The ID of an engine. Two builds with the same engine files have the same ID. On Linux it
/// is a part of the name of a folder.
#derive(Eq, Hash, Debug)
struct EngineId {
  text : String
}

///|
/// An ID has 1 to 80 lower-case letters, digits, periods and hyphens. It starts with a
/// letter.
pub fn EngineId::EngineId(text : String) -> EngineId raise ReleaseError {
  guard text.length() <= 80 &&
    text is ['a'..<='z', ..] &&
    text.iter().all(c => c is ('a'..<='z' | '0'..<='9' | '.' | '-')) else {
    raise InvalidEngineId(text)
  }
  { text, }
}

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

///|
/// One archive of a release.
#derive(Eq, Debug)
struct ArchiveFile {
  name : FileName
  size : Int64
  sha256 : Sha256
}

///|
/// The size is a number of bytes from 1 to 4 GB.
pub fn ArchiveFile::ArchiveFile(
  name : FileName,
  size : Double,
  sha256 : Sha256,
) -> ArchiveFile raise ReleaseError {
  guard size >= 1.0 && size <= 4294967296.0 && size.floor() == size else {
    raise InvalidSize(size)
  }
  { name, size: size.to_int64(), sha256, }
}

///|
pub fn ArchiveFile::name(self : ArchiveFile) -> FileName {
  self.name
}

///|
/// The size in bytes.
pub fn ArchiveFile::size(self : ArchiveFile) -> Int64 {
  self.size
}

///|
pub fn ArchiveFile::sha256(self : ArchiveFile) -> Sha256 {
  self.sha256
}

///|
/// The part of an archive that came from a source. It never has more bytes than the
/// archive.
#derive(Eq, Debug)
struct ReceivedPart {
  archive : ArchiveFile
  bytes : Int64
}

///|
/// The part before the first byte.
pub fn ReceivedPart::ReceivedPart(archive : ArchiveFile) -> ReceivedPart {
  { archive, bytes: 0L, }
}

///|
/// The part with these bytes at its end. `None` when the archive has not so many bytes.
pub fn ReceivedPart::add(
  self : ReceivedPart,
  chunk : BytesView,
) -> ReceivedPart? {
  let bytes = self.bytes + chunk.length().to_int64()
  guard bytes <= self.archive.size else { return None }
  Some({ ..self, bytes, })
}

///|
pub fn ReceivedPart::archive(self : ReceivedPart) -> ArchiveFile {
  self.archive
}

///|
/// The number of bytes, from 0 to the size of the archive.
pub fn ReceivedPart::bytes(self : ReceivedPart) -> Int64 {
  self.bytes
}

///|
/// True when the part has as many bytes as the archive.
pub fn ReceivedPart::is_complete(self : ReceivedPart) -> Bool {
  self.bytes == self.archive.size
}

///|
/// The archives of the app for one platform.
#derive(Eq, Debug)
pub(all) struct ReleaseFiles {
  /// Our programs and the small files.
  app : ArchiveFile
  engine_id : EngineId
  /// The files of the Chromium engine.
  engine : ArchiveFile
}

///|
/// The list of the files of one release.
#derive(Eq, Debug)
struct ReleaseList {
  version : @contracts.Version
  platforms : Map[AppPlatform, ReleaseFiles]
}

///|
pub fn ReleaseList::ReleaseList(
  version : @contracts.Version,
  platforms : Map[AppPlatform, ReleaseFiles],
) -> ReleaseList {
  { version, platforms: platforms.copy(), }
}

///|
pub fn ReleaseList::version(self : ReleaseList) -> @contracts.Version {
  self.version
}

///|
/// The archives for a platform. A release can have no app for it.
pub fn ReleaseList::files(
  self : ReleaseList,
  platform : AppPlatform,
) -> ReleaseFiles? {
  self.platforms.get(platform)
}

///|
/// Reads the text of `desktop.json`. The list of a later version can have more platforms
/// and more keys in the same format, so the function ignores those that it does not know.
pub fn ReleaseList::parse(text : String) -> ReleaseList raise ReleaseError {
  let json = @json.parse(text) catch { _ => raise WrongList("It is not JSON.") }
  guard json is { "format": Number(format, ..), .. } && format.floor() == format else {
    raise WrongList("It has no format.")
  }
  guard format >= 1.0 else { raise WrongList("Its format is \{format}.") }
  guard format <= list_format.to_double() else {
    raise NewerFormat(format.to_int())
  }
  guard json is { "version": String(version), .. } else {
    raise WrongList("It has no version.")
  }
  let version = @contracts.Version::Version(version) catch {
    InvalidVersion(text) => raise WrongList("'\{text}' is not a version.")
  }
  guard json is { "platforms": Object(entries), .. } else {
    raise WrongList("It has no platforms.")
  }
  let platforms = Map([])
  for name, entry in entries {
    guard AppPlatform::of_name(name) is Some(platform) else { continue }
    guard entry is { "app": app, "engine": engine, .. } &&
      engine is { "id": String(id), .. } else {
      raise WrongList("The entry \{name} does not have an app and an engine.")
    }
    platforms[platform] = ReleaseFiles::{
      app: archive_of(app, name),
      engine_id: EngineId(id),
      engine: archive_of(engine, name),
    }
  }
  { version, platforms, }
}

///|
fn archive_of(json : Json, platform : String) -> ArchiveFile raise ReleaseError {
  guard json
    is {
      "file": String(name),
      "size": Number(size, ..),
      "sha256": String(sha256),
      ..
    } else {
    raise WrongList(
      "An archive of \{platform} does not have a file, a size and a SHA-256.",
    )
  }
  ArchiveFile(FileName(name), size, Sha256(sha256))
}

///|
fn ArchiveFile::fields(self : ArchiveFile) -> Map[String, Json] {
  {
    "file": self.name.text,
    "size": Json::number(self.size.to_double()),
    "sha256": self.sha256.text,
  }
}

///|
/// The JSON form is the content of `desktop.json`.
pub impl ToJson for ReleaseList with fn to_json(self) {
  let platforms : Map[String, Json] = Map([])
  for platform in app_platforms {
    if self.files(platform) is Some(files) {
      let engine : Map[String, Json] = { "id": files.engine_id.text }
      for key, value in files.engine.fields() {
        engine[key] = value
      }
      platforms[platform.name()] = {
        "app": Json::object(files.app.fields()),
        "engine": Json::object(engine),
      }
    }
  }
  {
    "format": Json::number(list_format.to_double()),
    "version": self.version.to_json(),
    "platforms": Json::object(platforms),
  }
}

///|
/// The problem with a release, as text for people. The command adds which release it is.
pub fn ReleaseError::message(self : ReleaseError) -> String {
  match self {
    NewerFormat(format) =>
      "Its list has the format \{format}, and this command knows the formats up to \{list_format}."
    WrongList(text) => "Its list is wrong. \{text}"
    InvalidFileName(text) =>
      "Its list is wrong. '\{text}' is not the name of a file."
    InvalidSize(size) => "Its list is wrong. \{size} is not the size of a file."
    InvalidSha256(text) => "Its list is wrong. '\{text}' is not a SHA-256."
    InvalidEngineId(text) =>
      "Its list is wrong. '\{text}' is not the ID of an engine."
  }
}

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

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

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

///|
pub extend FileName with Hash::{hash, hash_combine}

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

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

///|
pub extend Sha256 with Hash::{hash, hash_combine}

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

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

///|
pub extend EngineId with Hash::{hash, hash_combine}

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

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

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

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

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

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

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

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

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

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