///|
/// Raised when a control request to a server has no success. The text is for people.
#derive(Eq, Debug)
pub(all) suberror ServerCallError {
  /// The server does not do the command, such as `/code/nope does not exist`.
  Refused(String)
  /// The server did not answer, it stops now, or only a newer version can use it. The
  /// server possibly did the command.
  NotReachable(String)
  /// The answer is not correct for this version of Mission Control.
  BadReply(String)
}

///|
/// A server that runs, as another program or the server itself knows it.
pub struct RunningServer {
  priv folder : @core.InstanceFolder
  priv version : @contracts.Version
  priv port : @core.Port
  /// Each control request needs it. Debug text never shows it.
  priv secret : @core.Secret
}

///|
/// The instance of the server.
pub fn RunningServer::instance(self : RunningServer) -> @app.InstanceName {
  self.folder.name()
}

///|
/// The version of the server. It can be another version than this program has.
pub fn RunningServer::version(self : RunningServer) -> @contracts.Version {
  self.version
}

///|
/// The port of `127.0.0.1` on which the server listens.
pub fn RunningServer::port(self : RunningServer) -> @core.Port {
  self.port
}

///|
/// The address of the server, such as `http://127.0.0.1:3090`.
pub fn RunningServer::address(self : RunningServer) -> String {
  self.port.address().to_string()
}

///|
/// How long a control request waits for the answer, when the server has no work to do
/// for it.
let answer_limit : Duration = Duration(10_000)

///|
/// How long a command waits for its answer. The system can need 40 seconds to search a
/// folder on a network share that is off.
let call_limit : Duration = Duration(60_000)

///|
/// How long `stop` waits for the end of the server. The open calls have 5 seconds.
let stop_limit : Duration = Duration(10_000)

///|
/// How long a program waits before it looks again at a server, a lock or a record.
let look_delay : Duration = Duration(50)

///|
/// The number of views that are connected to the server.
pub async fn RunningServer::views(
  self : RunningServer,
) -> Int32 raise ServerCallError {
  self.views_of(self.send(Get, "/control/status", answer_limit))
}

///|
/// Asks for a link that opens the UI, with the project when there is one. The link
/// gives access to the server for 10 minutes, so show it only to the user.
pub async fn RunningServer::link(
  self : RunningServer,
  surface : @app.Surface,
  project : @app.ProjectId?,
) -> String raise ServerCallError {
  let kind = match surface {
    Browser => "browser"
    Desktop => "desktop"
  }
  let project = match project {
    Some(id) => "&project=\{id.to_int()}"
    None => ""
  }
  let path = "/control/link?surface=\{kind}\{project}"
  let answer = self.send(Post, path, answer_limit)
  // The caller opens the link, so it must be an address of the server.
  guard answer.success() is { "url": String(link), .. } &&
    link.has_prefix("\{self.address()}/") else {
    raise BadReply("The server gave no link.")
  }
  link
}

///|
/// Does a command of the server and gives its reply. The name is the name in the
/// contract, such as `add_project`.
pub async fn RunningServer::call_json(
  self : RunningServer,
  name : String,
  request : Json,
) -> Json raise ServerCallError {
  let name = @percent.encode(name)
  let request = @percent.encode(request.stringify())
  let path = "/control/call?command=\{name}&request=\{request}"
  self.send(Post, path, call_limit).success()
}

///|
/// Does a command of the contract, such as `@app.add_project`, and gives its reply.
pub async fn[Req : ToJson, Res : @json.FromJson] RunningServer::call(
  self : RunningServer,
  command : @proton_contract.Command[Req, Res],
  request : Req,
) -> Res raise ServerCallError {
  let name = command.name()
  let reply = self.call_json(name, request.to_json())
  @json.from_json(reply) catch {
    _ => raise BadReply("The reply to \{name} has another form.")
  }
}

///|
/// Stops the server, and returns when it has ended. A new server of the instance can
/// then start on the same port, and this function does not wait for that one.
///
/// This needs 10 seconds at most, and raises `NotReachable` when the server did not end.
/// A server that ended before is no failure.
pub async fn RunningServer::stop(
  self : RunningServer,
) -> Unit raise ServerCallError {
  self.stop_in(stop_limit)
}

///|
/// Stops the server in a limited time.
async fn RunningServer::stop_in(
  self : RunningServer,
  limit : Duration,
) -> Unit raise ServerCallError {
  let end = limit.after(@async.now())
  // A server that ended gets no request. Another program can have its port.
  guard !self.has_ended() else { return }
  let failure = try self.send(Post, "/control/stop", limit).success() catch {
    // The server can end before the answer comes, and then another program can answer.
    // So no answer says that the server still runs.
    error => error
  } noraise {
    _ => NotReachable("The server did not end in \{limit.to_text()}.")
  }
  while !self.has_ended() {
    guard @async.now() < end else { raise failure }
    @async.sleep(look_delay.millis())
  }
}

///|
/// True when the server has ended: no process has the lock of the instance, or another
/// process wrote the record. Only the process with the lock writes it. The lock is not
/// sufficient, because another program can start a new server between two looks.
async fn RunningServer::has_ended(self : RunningServer) -> Bool noraise {
  let is_free = lock_is_free(self.folder) catch { _ => false }
  is_free ||
  (match read_record(self.folder) {
    Known(Running(secret~, ..)) => secret != self.secret
    Known(Failed(..)) | Newer(_) => true
    NoRecord => false
  })
}

///|
/// The number of views in an answer to `GET /control/status`. Raises when the program
/// that answered is not the server.
fn RunningServer::views_of(
  self : RunningServer,
  answer : ControlAnswer,
) -> Int32 raise ServerCallError {
  let other = BadReply("Another program has the port \{self.port.to_int()}.")
  guard answer.success()
    is {
      "app": String("mission-control"),
      "instance": String(instance),
      "views": views,
      ..
    } &&
    instance == self.instance().to_string() else {
    raise other
  }
  @json.from_json(views) catch {
    _ => raise other
  }
}

///|
/// The answer to a control request.
priv struct ControlAnswer {
  status : Int32
  text : String
}

///|
/// Sends a control request. The secret goes to the port of the server on this machine
/// only. Raises `NotReachable` when no complete answer comes in the limit.
async fn RunningServer::send(
  self : RunningServer,
  method_ : @http.RequestMethod,
  path : String,
  limit : Duration,
) -> ControlAnswer raise ServerCallError {
  let late = NotReachable("The server did not answer in \{limit.to_text()}.")
  @async.with_timeout(limit.millis(), error=late, () => {
    let client = @http.Client(self.address(), headers={
      "X-Mission-Control-Secret": self.secret.to_text(),
    })
    defer client.close()
    client.request(method_, path)
    let status = client.end_request().code
    { status, text: @utf8.decode_lossy(client.read_all().binary()), }
  }) catch {
    NotReachable(_) as error => raise error
    @os_error.OSError(_) as error => raise NotReachable(reason_of(error))
    @http.HttpProtocolError::BadRequest
    | @http.HttpProtocolError::HttpVersionNotSupported(_)
    | @http.HttpProtocolError::NotImplemented =>
      raise BadReply("The answer is not HTTP.")
    _ => raise NotReachable("The connection ended before the answer.")
  }
}

///|
/// The JSON of an answer with success, or the error that the status and the text say.
fn ControlAnswer::success(self : ControlAnswer) -> Json raise ServerCallError {
  let json = Some(@json.parse(self.text)) catch { _ => None }
  let text = match json {
    Some({ "error": String(text), .. }) if !text.is_empty() => Some(text)
    _ => None
  }
  match (self.status, json) {
    (200 | 202, Some(json)) => json
    (200 | 202, None) => raise BadReply("The answer is not JSON.")
    (422, _) => raise Refused(text.unwrap_or("The server refused the command."))
    (503, _) => raise NotReachable(text.unwrap_or("The server stops now."))
    // A server of Mission Control that started later, or of another instance.
    (403, _) => raise NotReachable("Another server has the port now.")
    (status, _) => {
      let answer = "The server answered with the status \{status}."
      raise BadReply(
        match text {
          Some(text) => "\{answer} \{text}"
          None => answer
        },
      )
    }
  }
}

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

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