///|
/// The name of the session cookie of one server, such as `mc_stable_3090`.
///
/// A browser sends a cookie to each port of the machine, so the name has the
/// instance and the port. Both parts have only characters that a cookie name
/// can have.
#derive(Eq, Debug)
struct CookieName {
  text : String
}

///|
/// Makes the cookie name of a server.
pub fn CookieName::CookieName(
  instance : @app.InstanceName,
  port : Port,
) -> CookieName {
  { text: "mc_\{instance.to_string()}_\{port.to_int()}", }
}

///|
/// The values of all cookies with this name in a `Cookie` header.
///
/// The header is `name=value` pairs with `;` between them. Other cookies and
/// text that is not a pair are ignored.
fn CookieName::values(
  self : CookieName,
  cookie_header : String?,
) -> Array[String] {
  guard cookie_header is Some(header) else { return [] }
  let values = []
  for pair in header.split(";") {
    if pair.trim(chars=" \t").split_once("=") is Some((name, value)) &&
      name == self.text {
      values.push(value.to_owned())
    }
  }
  values
}

///|
/// A session has two secrets. The browser sends the cookie to each port of the
/// machine, so another local server can read it. The browser keeps the view key
/// in the storage of the origin of the server, so another server cannot read it.
#derive(Eq, Debug)
priv struct Session {
  cookie : Secret
  key : Secret
  surface : @app.Surface
}

///|
/// The sessions that the server gave. A session is valid until the server ends.
#derive(Eq, Debug)
struct Sessions {
  sessions : Array[Session]
}

///|
/// No sessions.
pub fn Sessions::empty() -> Sessions {
  { sessions: [], }
}

///|
/// Adds a session with a new cookie value and a new view key. The two secrets
/// come from different random bytes: with equal secrets, the cookie is also the
/// key.
pub fn Sessions::add(
  self : Sessions,
  cookie~ : Secret,
  key~ : Secret,
  surface : @app.Surface,
) -> Sessions {
  { sessions: [..self.sessions, { cookie, key, surface, }], }
}

///|
/// The kind of view of the session in a `Cookie` header, or `None` if the
/// header has no valid session.
///
/// Use this function only for the static page and its script. Another local
/// server can read the cookie, so the cookie alone must not give data or
/// control. The hub and the session check use `find_view`.
///
/// If the header has several cookies of this name, each one is tried, and the
/// first valid one wins.
pub fn Sessions::find(
  self : Sessions,
  name : CookieName,
  cookie_header : String?,
) -> @app.Surface? {
  let mut found = None
  // The loops compare each session, so the time does not tell which one
  // matches.
  for value in name.values(cookie_header) {
    for session in self.sessions {
      if session.cookie.matches(value) && found is None {
        found = Some(session.surface)
      }
    }
  }
  found
}

///|
/// The kind of view of a request for the hub or for the session check, or `None`
/// if the request does not have the cookie and the view key of one session.
///
/// The cookie of one session with the key of another session gives `None`. If
/// the header has several cookies of this name, each one is tried with the key.
pub fn Sessions::find_view(
  self : Sessions,
  name : CookieName,
  cookie_header~ : String?,
  key~ : String?,
) -> @app.Surface? {
  guard key is Some(key) else { return None }
  let mut found = None
  // As in `find`, the loops compare each session. Both secrets are compared
  // before the decision, so the time does not tell which one is right.
  for value in name.values(cookie_header) {
    for session in self.sessions {
      let has_cookie = session.cookie.matches(value)
      let has_key = session.key.matches(key)
      if has_cookie && has_key && found is None {
        found = Some(session.surface)
      }
    }
  }
  found
}

///|
/// The kind of view of the session with this view key, or `None` if no session has it.
///
/// This is not a login. Use it only for a request that `find_view` accepted, when the
/// cookie is not there any more.
pub fn Sessions::surface_of(self : Sessions, key : String) -> @app.Surface? {
  let mut found = None
  // As in `find`, the loop compares each session.
  for session in self.sessions {
    if session.key.matches(key) {
      found = Some(session.surface)
    }
  }
  found
}

///|
/// The value of the `Set-Cookie` header for a new session. It has the cookie
/// value of the session, and never the view key.
///
/// The cookie has no end time and no domain: the browser keeps it until the
/// browser closes, and sends it to `127.0.0.1` only, but to each port. A script
/// cannot read it, and a request from another site does not have it.
pub fn set_cookie(name : CookieName, cookie : Secret) -> String {
  "\{name.text}=\{cookie.to_text()}; Path=/; HttpOnly; SameSite=Strict"
}

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

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

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

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