///|
/// How a connection starts.
#derive(Eq, Debug)
pub(all) enum HttpScheme {
  Http
  Https
}

///|
/// The text before `://`.
pub fn HttpScheme::name(self : HttpScheme) -> String {
  match self {
    Http => "http"
    Https => "https"
  }
}

///|
fn HttpScheme::default_port(self : HttpScheme) -> Int32 {
  match self {
    Http => 80
    Https => 443
  }
}

///|
/// Raised when a text is not the name of a host. It has the text.
#derive(Eq, Debug)
pub(all) suberror HostNameError {
  InvalidHostName(String)
}

///|
/// The name or the IP address of a host, in lower case. An IPv6 address has its brackets.
#derive(Eq, Debug)
struct HostName {
  text : String
}

///|
/// A name has 1 to 253 ASCII letters, digits, hyphens and underscores, with periods between
/// its parts. A period at the end goes. An IPv6 address is in brackets.
pub fn HostName::HostName(text : String) -> HostName raise HostNameError {
  let name = text.to_lower()
  let name = match name {
    [.. rest, '.'] => rest.to_owned()
    _ => name
  }
  let is_valid = match name {
    ['[', .. address, ']'] =>
      address.contains(":") &&
      address.iter().all(c => c is ('0'..<='9' | 'a'..<='f' | ':' | '.'))
    _ =>
      name.length() <= 253 &&
      name
      .split(".")
      .all(part => {
        !part.is_empty() &&
        part.iter().all(c => c is ('0'..<='9' | 'a'..<='z' | '-' | '_'))
      })
  }
  guard is_valid else { raise InvalidHostName(text) }
  { text: name, }
}

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

///|
/// True for a name or an address that is always this machine.
pub fn HostName::is_loopback(self : HostName) -> Bool {
  match self.text {
    "localhost" | "[::1]" => true
    text =>
      text.has_prefix("127.") &&
      text.split(".").count() == 4 &&
      text.split(".").all(part => part.iter().all(c => c is ('0'..<='9')))
  }
}

///|
/// Hosts to which the command connects without the proxy.
#derive(Eq, Debug)
pub(all) enum HostRule {
  /// `*`
  AnyHost
  /// The host and its subdomains.
  HostAndBelow(HostName)
}

///|
/// Reads one entry of `no_proxy`: `*` or a host name. `.example.com` and `*.example.com` are
/// other forms of `example.com`.
pub fn HostRule::parse(text : String) -> HostRule raise HostNameError {
  match text {
    "*" => AnyHost
    ['*', '.', .. name] | ['.', .. name] =>
      HostAndBelow(HostName(name.to_owned())) catch {
        _ => raise InvalidHostName(text)
      }
    _ => HostAndBelow(HostName(text))
  }
}

///|
pub fn HostRule::matches(self : HostRule, host : HostName) -> Bool {
  match self {
    AnyHost => true
    HostAndBelow(name) =>
      host.text == name.text || host.text.has_suffix(".\{name.text}")
  }
}

///|
/// The parts of an address after its scheme.
priv struct AddressParts {
  scheme : HttpScheme
  login : String?
  host : HostName
  port : @core.Port
  /// The path, the query and the fragment. Empty, or it starts with `/`, `?` or `#`.
  rest : String
}

///|
/// Why a text is not an address of the two schemes.
priv suberror AddressPartsError {
  OtherScheme
  NotAddress
}

///|
fn AddressParts::parse(text : String) -> AddressParts raise AddressPartsError {
  guard text.split_once("://") is Some((scheme, after)) else {
    raise NotAddress
  }
  let scheme : HttpScheme = match scheme.to_owned().to_lower() {
    "http" => Http
    "https" => Https
    _ => raise OtherScheme
  }
  let mut end = 0
  for c in after {
    if c is ('/' | '?' | '#') {
      break
    }
    end += c.utf16_len()
  }
  let rest = after[end:].to_owned()
  // Such a character could end the line of a request.
  guard rest.iter().all(c => c is ('!'..<='~')) else { raise NotAddress }
  let (login, place) = match after[:end].rev_split_once("@") {
    Some((login, place)) => (Some(login.to_owned()), place)
    None => (None, after[:end])
  }
  let (host, port) = match place {
    ['[', ..] =>
      match place.rev_split_once("]") {
        Some((host, "")) => ("\{host}]", None)
        Some((host, [':', .. port])) => ("\{host}]", Some(port))
        _ => raise NotAddress
      }
    _ =>
      match place.split_once(":") {
        Some((host, port)) => (host.to_owned(), Some(port))
        None => (place.to_owned(), None)
      }
  }
  let host = HostName(host) catch { _ => raise NotAddress }
  let number = match port {
    None => scheme.default_port()
    Some(digits) => {
      guard digits.length() is (1..<=5) &&
        digits.iter().all(c => c is ('0'..<='9')) else {
        raise NotAddress
      }
      digits
      .iter()
      .fold(init=0, (value, c) => value * 10 + (c.to_int() - '0'.to_int()))
    }
  }
  let port = @core.Port(number) catch { _ => raise NotAddress }
  { scheme, login, host, port, rest, }
}

///|
/// The address without its path, such as `https://example.com`. It has a port only when the
/// port is not the one of the scheme.
fn origin_text(
  scheme : HttpScheme,
  host : HostName,
  port : @core.Port,
) -> String {
  let start = "\{scheme.name()}://\{host.text}"
  if port.to_int() == scheme.default_port() {
    start
  } else {
    "\{start}:\{port.to_int()}"
  }
}

///|
/// A wrong address for people, without a user name, a password, a query and a fragment.
fn shown_address(text : String) -> String {
  let (start, after) = match text.split_once("://") {
    Some((scheme, after)) => ("\{scheme}://", after)
    None => ("", text[:])
  }
  let after = match after.split_once("?") {
    Some((path, _)) => path
    None => after
  }
  let after = match after.split_once("#") {
    Some((path, _)) => path
    None => after
  }
  let after = match after.rev_split_once("@") {
    Some((_, place)) => place
    None => after
  }
  "\{start}\{after}"
}

///|
/// Raised when the address of a proxy is wrong. No text in it has a login.
#derive(Eq, Debug)
pub(all) suberror ProxyAddressError {
  /// The address has a user name or a password.
  LoginInAddress
  /// The address has another scheme, such as `socks5`.
  OtherProxyType(String)
  NotProxyAddress(String)
}

///|
/// The problem, as text for people.
pub fn ProxyAddressError::message(self : ProxyAddressError) -> String {
  match self {
    LoginInAddress =>
      "The address of a proxy must have no user name and no password."
    OtherProxyType(text) =>
      "\{text} is not an HTTP proxy. The address of a proxy starts with http:// or https://."
    NotProxyAddress(text) =>
      "'\{text}' is not the address of a proxy, such as http://proxy.example.com:8080."
  }
}

///|
/// The address of an HTTP proxy: `http://` or `https://`, a host and a port. Without a port,
/// it is the one of the scheme.
#derive(Eq, Debug)
struct ProxyAddress {
  scheme : HttpScheme
  host : HostName
  port : @core.Port
}

///|
/// Reads an address that also can have a login, as in a variable of the shell.
fn proxy_parts(
  text : String,
) -> (ProxyAddress, String?) raise ProxyAddressError {
  let parts = AddressParts::parse(text) catch {
    OtherScheme => raise OtherProxyType(shown_address(text))
    NotAddress => raise NotProxyAddress(shown_address(text))
  }
  guard parts.rest is ("" | "/") else {
    raise NotProxyAddress(shown_address(text))
  }
  let { scheme, host, port, login, .. } = parts
  ({ scheme, host, port, }, login)
}

///|
/// Reads the address in a setting. It has no login, because a file is not a place for a
/// password.
pub fn ProxyAddress::parse(
  text : String,
) -> ProxyAddress raise ProxyAddressError {
  // Also a wrong address with a login is a login in a file.
  guard !text.contains("@") else { raise LoginInAddress }
  proxy_parts(text).0
}

///|
pub fn ProxyAddress::to_string(self : ProxyAddress) -> String {
  origin_text(self.scheme, self.host, self.port)
}

///|
/// Raised when a text is not a login. It does not have the text.
#derive(Eq, Debug)
pub(all) suberror ProxyLoginError {
  InvalidProxyLogin
}

///|
/// The user name and the password for a proxy. `Debug` does not show them.
#derive(Eq)
struct ProxyLogin {
  text : String
}

///|
/// Reads a user name and a password with `:` between them. The password can have a `:`.
pub fn ProxyLogin::parse(text : String) -> ProxyLogin raise ProxyLoginError {
  guard text.split_once(":") is Some((user, _)) &&
    !user.is_empty() &&
    text.iter().all(c => !(c is ('\u{0}'..<='\u{1f}' | '\u{7f}'))) else {
    raise InvalidProxyLogin
  }
  { text, }
}

///|
/// The user name and the password with `:` between them, for the header of a request. Do not
/// show it.
pub fn ProxyLogin::expose(self : ProxyLogin) -> String {
  self.text
}

///|
pub impl @debug.Debug for ProxyLogin with fn to_repr(_) {
  @debug.Repr("")
}

///|
/// Raised when an address for files is wrong. No text in it has a login or a query.
#derive(Eq, Debug)
pub(all) suberror FileAddressError {
  /// The address is not encrypted, and its host is not this machine.
  NotEncrypted(String)
  NotFileAddress(String)
}

///|
/// The problem, as text for people.
pub fn FileAddressError::message(self : FileAddressError) -> String {
  match self {
    NotEncrypted(text) =>
      "The connection to \{text} is not encrypted. The address must start with https://."
    NotFileAddress(text) =>
      "'\{text}' is not an address with https://, without a user name and a password."
  }
}

///|
/// The address of a file that the command downloads. It is encrypted, or its host is this
/// machine. A query can have a token, so `shown` gives the address for people.
struct FileAddress {
  scheme : HttpScheme
  host : HostName
  port : @core.Port
  path : String
  query : String
}

///|
pub fn FileAddress::parse(text : String) -> FileAddress raise FileAddressError {
  let parts = AddressParts::parse(text) catch {
    OtherScheme => raise NotEncrypted(shown_address(text))
    NotAddress => raise NotFileAddress(shown_address(text))
  }
  guard parts.login is None else { raise NotFileAddress(shown_address(text)) }
  guard parts.scheme is Https || parts.host.is_loopback() else {
    raise NotEncrypted(shown_address(text))
  }
  let rest = match parts.rest.split_once("#") {
    Some((rest, _)) => rest
    None => parts.rest
  }
  let (path, query) = match rest.split_once("?") {
    Some((path, query)) => (path, "?\{query}")
    None => (rest, "")
  }
  let { scheme, host, port, .. } = parts
  {
    scheme,
    host,
    port,
    path: if path.is_empty() {
      "/"
    } else {
      path.to_owned()
    },
    query,
  }
}

///|
/// True when a location starts with a scheme, such as `https:`. The first part of a relative
/// path has no `:`.
fn has_scheme(location : String) -> Bool {
  for c in location {
    match c {
      ':' => return true
      '/' | '?' | '#' => return false
      _ => ()
    }
  }
  false
}

///|
/// An absolute path without its parts `.` and `..`. Nothing is above the root.
fn without_dots(path : String) -> String {
  let names : Array[StringView] = []
  let parts = path[1:].split("/").collect()
  for i, part in parts {
    let is_last = i == parts.length() - 1
    match part {
      "." | ".." => {
        if part == ".." {
          ignore(names.pop())
        }
        // The path is a folder then, and it keeps its `/` at the end.
        if is_last {
          names.push("")
        }
      }
      _ => names.push(part)
    }
  }
  "/\{names.join("/")}"
}

///|
/// The address to which a server sends the command. `location` is a complete address, or it
/// starts at this address, as in RFC 3986: `/a` is on the same server, `a` and `../a` start
/// at the folder of the file, and `?a` is the same file with another query.
pub fn FileAddress::redirect(
  self : FileAddress,
  location : String,
) -> FileAddress raise FileAddressError {
  if location.has_prefix("//") {
    return FileAddress::parse("\{self.scheme.name()}:\{location}")
  }
  if has_scheme(location) {
    return FileAddress::parse(location)
  }
  let mut end = 0
  for c in location {
    if c is ('?' | '#') {
      break
    }
    end += c.utf16_len()
  }
  let rest = location[end:]
  let target = match location[:end] {
    "" if rest is ['?', ..] => "\{self.path}\{rest}"
    "" => self.target()
    ['/', ..] as path => "\{without_dots(path.to_owned())}\{rest}"
    path => {
      let folder = match self.path.rev_split_once("/") {
        Some((folder, _)) => folder
        None => ""
      }
      "\{without_dots("\{folder}/\{path}")}\{rest}"
    }
  }
  FileAddress::parse("\{self.origin()}\{target}")
}

///|
pub fn FileAddress::host(self : FileAddress) -> HostName {
  self.host
}

///|
/// The scheme, the host and the port, such as `https://example.com`.
pub fn FileAddress::origin(self : FileAddress) -> String {
  origin_text(self.scheme, self.host, self.port)
}

///|
/// The path and the query, for a request. Do not show it.
pub fn FileAddress::target(self : FileAddress) -> String {
  "\{self.path}\{self.query}"
}

///|
/// The address for people and for a log, without its query.
pub fn FileAddress::shown(self : FileAddress) -> String {
  "\{self.origin()}\{self.path}"
}

///|
/// The address of a mirror with the releases of the app, such as
/// `https://mirror.example.com/mission-control`. It is encrypted, or its host is this
/// machine, and it has no login and no query.
#derive(Eq, Debug)
struct SourceAddress {
  text : String
}

///|
/// A `/` at the end goes.
pub fn SourceAddress::parse(
  text : String,
) -> SourceAddress raise FileAddressError {
  guard !text.contains("?") && !text.contains("#") else {
    raise NotFileAddress(shown_address(text))
  }
  let address = FileAddress::parse(text).shown()
  { text: address.trim_end(chars="/").to_owned(), }
}

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

///|
/// A folder with the files of one release.
#derive(Eq, Debug)
pub(all) enum ReleaseFolder {
  LatestFolder
  VersionFolder(@contracts.Version)
}

///|
/// Where the releases are.
#derive(Eq, Debug)
pub(all) enum ReleaseSite {
  /// The GitHub releases of Mission Control.
  GitHub
  /// The newest release is in the folder `latest`, and the version 0.6.0 in `v0.6.0`.
  Mirror(SourceAddress)
}

///|
/// The page of the releases on GitHub.
let github_releases : String = "https://github.com/moonrockz/mission-control/releases"

///|
/// The address of the site.
pub fn ReleaseSite::to_string(self : ReleaseSite) -> String {
  match self {
    GitHub => github_releases
    Mirror(address) => address.text
  }
}

///|
/// The address of a file of a release.
pub fn ReleaseSite::file(
  self : ReleaseSite,
  folder : ReleaseFolder,
  name : FileName,
) -> FileAddress raise FileAddressError {
  let folder = match (self, folder) {
    (GitHub, LatestFolder) => "latest/download"
    (GitHub, VersionFolder(version)) => "download/v\{version.to_string()}"
    (Mirror(_), LatestFolder) => "latest"
    (Mirror(_), VersionFolder(version)) => "v\{version.to_string()}"
  }
  FileAddress::parse("\{self.to_string()}/\{folder}/\{name.to_string()}")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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