///|
/// The stop of a server. The first one who asks starts it.
priv struct StopRequest {
  mut requested : Bool
  change : @cond_var.Cond
}

///|
/// A stop that nobody asked for.
fn StopRequest::StopRequest() -> StopRequest {
  { requested: false, change: Cond(), }
}

///|
/// Asks for the stop, and returns at once.
fn StopRequest::request(self : StopRequest) -> Unit {
  self.requested = true
  self.change.broadcast()
}

///|
/// Waits until somebody asks for the stop.
async fn StopRequest::wait(self : StopRequest) -> Unit {
  while !self.requested {
    self.change.wait()
  }
}

///|
/// The requests of one server: who can send one, and what the server does with it.
priv struct Site {
  app : App
  login : Login
  views : Views
  stop : StopRequest
  log : async (String) -> Unit noraise
  /// The number of calls that run.
  mut calls : Int32
  /// Wakes the stop when no call runs.
  idle : @cond_var.Cond
}

///|
/// Does a command, for the hub and for a control request. After the stop, only a
/// second `stop_app` gets its reply.
async fn Site::call(self : Site, name : String, request : Json) -> Json {
  guard !self.stop.requested || name == @app.stop_app.name() else {
    raise stops_now()
  }
  self.calls += 1
  defer {
    self.calls -= 1
    if self.calls == 0 {
      self.idle.broadcast()
    }
  }
  self.app.call(name, request)
}

///|
/// Waits until no call runs, for a limited time.
async fn Site::finish_calls(self : Site, limit : Duration) -> Unit {
  @async.with_timeout_opt(limit.millis(), () => {
    while self.calls > 0 {
      self.idle.wait()
    }
  })
  |> ignore
}

///|
/// What the HTTP server does with the requests and the calls.
fn Site::handlers(self : Site) -> Handlers {
  {
    is_same_site: request => self.login.is_same_site(request),
    is_view: request => self.login.is_view(request, hub_key(request)),
    surface_of: key => self.login.surface_of(key),
    greeting: surface => {
      self.app
      .greeting(surface)
      .map(shown => (@app.project_shown.name(), shown.to_json()))
    },
    answer: request => self.answer(request),
    call: (name, request) => self.call(name, request),
  }
}

///|
/// Answers a request for a path that is not of the hub. The HTTP server already
/// refused the requests of other sites.
async fn Site::answer(self : Site, request : Request) -> Reply {
  self.route(request) catch {
    error => {
      // The log does not get the request, because an address can have a secret.
      (self.log)("A request failed: \{reason_of(error)}")
      Reply(InternalError)
    }
  }
}

///|
/// Each path of the server has one method and one login. No path gives a file, so
/// the content of a project never comes from this origin.
async fn Site::route(self : Site, request : Request) -> Reply {
  match (request.path, request.method_) {
    ("/", Get) => self.page(request)
    ("/app.js", Get) =>
      self.after_login(self.login.page_view(request) is Some(_), () => {
        Reply(
          Success,
          kind="text/javascript; charset=utf-8",
          body=@utf8.encode(@ui.app_js),
        )
      })
    ("/session", Get) =>
      self.after_login(self.login.is_view(request, header_key(request)), () => {
        Reply(NoContent)
      })
    ("/control/status", Get) => self.control(request, () => self.status())
    ("/control/link", Post) => self.control(request, () => self.link(request))
    ("/control/call", Post) =>
      self.control(request, () => self.control_call(request))
    ("/control/stop", Post) =>
      self.control(request, stopping=true, () => {
        self.stop.request()
        Reply::json(Accepted, {})
      })
    (
      "/"
      | "/app.js"
      | "/session"
      | "/control/status"
      | "/control/link"
      | "/control/call"
      | "/control/stop",
      _,
    ) => Reply(MethodNotAllowed)
    _ => Reply(NotFound)
  }
}

///|
/// The page that a link opens, the page of the UI, or the page that says how to get
/// a link.
fn Site::page(self : Site, request : Request) -> Reply raise NoRandomBytes {
  guard !self.stop.requested else { return stops_now_reply() }
  let instance = self.app.folder.name()
  match (request.query)("access_token") {
    Some(token) =>
      match self.login.redeem(token) {
        Some(entrance) => entrance_page(instance, entrance)
        // A session of this browser does not count: the user must know that the
        // link does not work.
        None => no_session_page(instance)
      }
    None =>
      match self.login.page_view(request) {
        Some(surface) => ui_page(instance, self.login.port, surface)
        None => no_session_page(instance)
      }
  }
}

///|
/// The reply to a request that needs a login. After the stop, the server does no new
/// work, if `stopping` is not true.
async fn Site::after_login(
  self : Site,
  has_login : Bool,
  reply : async () -> Reply,
  stopping~ : Bool = false,
) -> Reply {
  guard has_login else {
    return Reply::error(Forbidden, "The request has no valid login.")
  }
  guard !self.stop.requested || stopping else { return stops_now_reply() }
  reply()
}

///|
/// The reply to a control request. It needs the secret and has no body.
async fn Site::control(
  self : Site,
  request : Request,
  reply : async () -> Reply,
  stopping~ : Bool = false,
) -> Reply {
  self.after_login(self.login.is_program(request), stopping~, () => {
    if request.has_body() {
      Reply::error(TooLarge, "The request must have no body.")
    } else {
      reply()
    }
  })
}

///|
/// The reply to a new request after the stop.
fn stops_now_reply() -> Reply {
  let Refusal(text) = stops_now()
  Reply::error(Unavailable, text)
}