///|
/// The reason why a server did not start.
#derive(Eq, Debug)
pub(all) enum StartFailure {
  /// Another program uses the port.
  PortInUse(Port)
  /// The server cannot use the project file. The path and the message are text
  /// to show, and have no rules here.
  BadProjectFile(path~ : String, message~ : String)
  /// Another reason, as text to show.
  Other(String)
}

///|
/// The content of `server.json`: how to reach the server of an instance, or why
/// it did not start.
#derive(Eq, Debug)
pub(all) enum ServerRecord {
  /// The server listens on the port. A control request needs the secret.
  Running(port~ : Port, version~ : @contracts.Version, secret~ : Secret)
  /// The start failed at this time.
  Failed(at~ : @app.UnixMillis, failure~ : StartFailure)
}

///|
/// What is wrong in a damaged record. It never has a value of the record,
/// because the value can be the secret.
#derive(Eq, Debug)
pub(all) enum RecordDamage {
  /// The text is not complete and valid JSON.
  NotJson
  /// The JSON value is not an object.
  NotObject
  /// The field with this name is absent, or its value breaks a rule.
  BadField(String)
}

///|
/// Raised when a text is not a server record that this version can read.
#derive(Eq, Debug)
pub(all) suberror ServerRecordError {
  /// The text is not a record of format 1.
  Damaged(RecordDamage)
  /// The record has a format that is newer than this version knows. A format
  /// above 2147483647 has the value 2147483647 here.
  NewerFormat(Int32)
}

///|
/// The format that `to_text` writes.
let record_format : Int32 = 1

///|
/// The JSON text of the record. The text of a server that runs has its secret,
/// so it must only go to the private file.
pub fn ServerRecord::to_text(self : ServerRecord) -> String {
  let fields : Map[String, Json] = { "format": ToJson::to_json(record_format) }
  match self {
    Running(port~, version~, secret~) => {
      fields["state"] = "running"
      fields["port"] = ToJson::to_json(port.to_int())
      fields["version"] = version.to_json()
      fields["secret"] = Json::string(secret.to_text())
    }
    Failed(at~, failure~) => {
      fields["state"] = "failed"
      fields["at"] = at.to_json()
      match failure {
        PortInUse(port) => {
          fields["failure"] = "port_in_use"
          fields["port"] = ToJson::to_json(port.to_int())
        }
        BadProjectFile(path~, message~) => {
          fields["failure"] = "bad_project_file"
          fields["path"] = Json::string(path)
          fields["message"] = Json::string(message)
        }
        Other(message) => {
          fields["failure"] = "other"
          fields["message"] = Json::string(message)
        }
      }
    }
  }
  Json::object(fields).stringify()
}

///|
/// Reads a field of a record. The error of the JSON decoder is left out, because
/// it can have the value.
fn[T : @json.FromJson] record_field(
  fields : Map[String, Json],
  key : String,
) -> T raise ServerRecordError {
  guard fields.get(key) is Some(json) else { raise Damaged(BadField(key)) }
  @json.from_json(json) catch {
    _ => raise Damaged(BadField(key))
  }
}

///|
fn record_port(fields : Map[String, Json]) -> Port raise ServerRecordError {
  Port::Port(record_field(fields, "port")) catch {
    _ => raise Damaged(BadField("port"))
  }
}

///|
fn record_failure(
  fields : Map[String, Json],
) -> StartFailure raise ServerRecordError {
  let failure : String = record_field(fields, "failure")
  match failure {
    "port_in_use" => PortInUse(record_port(fields))
    "bad_project_file" =>
      BadProjectFile(
        path=record_field(fields, "path"),
        message=record_field(fields, "message"),
      )
    "other" => Other(record_field(fields, "message"))
    _ => raise Damaged(BadField("failure"))
  }
}

///|
/// Reads the text that `to_text` gives. Unknown fields are ignored.
///
/// The format number is read first: a whole number above 1 raises `NewerFormat`,
/// whatever the other fields are. Each other fault raises `Damaged`.
pub fn ServerRecord::of_text(
  text : String,
) -> ServerRecord raise ServerRecordError {
  let json = @json.parse(text) catch { _ => raise Damaged(NotJson) }
  guard json is Object(fields) else { raise Damaged(NotObject) }
  let { format, } : SavedFormat = @json.from_json(json) catch {
    _ => raise Damaged(BadField("format"))
  }
  guard format <= record_format else { raise NewerFormat(format) }
  let state : String = record_field(fields, "state")
  match state {
    "running" => {
      let port = record_port(fields)
      let version : @contracts.Version = record_field(fields, "version")
      guard Secret::of_text(record_field(fields, "secret")) is Some(secret) else {
        raise Damaged(BadField("secret"))
      }
      Running(port~, version~, secret~)
    }
    "failed" => {
      let at : @app.UnixMillis = record_field(fields, "at")
      Failed(at~, failure=record_failure(fields))
    }
    _ => raise Damaged(BadField("state"))
  }
}

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

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

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

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

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

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

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

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