///|
/// The proxy that a user selects in the configuration.
#derive(Eq, Debug)
pub(all) enum ProxyChoice {
  /// The variables of the shell give the proxy, as for other programs.
  FromVariables
  NoProxy
  Use(ProxyAddress)
}

///|
/// Reads the setting `download.proxy`: an address, or `none`.
pub fn ProxyChoice::parse(text : String) -> ProxyChoice raise ProxyAddressError {
  if text == "none" {
    NoProxy
  } else {
    Use(ProxyAddress::parse(text))
  }
}

///|
/// A proxy and the login for it.
#derive(Eq, Debug)
pub(all) struct Proxy {
  address : ProxyAddress
  login : ProxyLogin?
}

///|
/// Raised when a variable of the shell has a wrong proxy.
#derive(Eq, Debug)
pub(all) suberror ProxyVariableError {
  WrongProxyVariable(variable~ : String, ProxyAddressError)
}

///|
/// The problem, as text for people.
pub fn ProxyVariableError::message(self : ProxyVariableError) -> String {
  match self {
    WrongProxyVariable(variable~, error) =>
      "The environment variable \{variable} has a wrong proxy. \{error.message()}"
  }
}

///|
/// Which proxy the command uses for a host.
#derive(Eq, Debug)
struct ProxyRules {
  proxy : Proxy?
  direct : ReadOnlyArray[HostRule]
}

///|
/// The value of the first variable that is not empty, with the name that the shell has. The
/// names are in upper case, and each one also counts in lower case.
fn variable(
  env_vars : Map[String, String],
  names : ArrayView[String],
) -> (String, String)? {
  for name in names {
    for name in [name, name.to_lower()] {
      if env_vars.get(name) is Some(value) && !value.trim().is_empty() {
        return Some((name, value.trim().to_owned()))
      }
    }
  }
  None
}

///|
/// The text of a login in an address, where `%40` is `@`. A wrong code stays as it is.
fn percent_decoded(text : String) -> String {
  let bytes = @utf8.encode(text)
  let out = []
  for i = 0; i < bytes.length(); {
    let digits = if bytes[i] == b'%' && i + 2 < bytes.length() {
      (hex_digit(bytes[i + 1]), hex_digit(bytes[i + 2]))
    } else {
      (None, None)
    }
    if digits is (Some(high), Some(low)) {
      out.push((high * 16 + low).to_byte())
      continue i + 3
    }
    out.push(bytes[i])
    continue i + 1
  }
  @utf8.decode_lossy(Bytes::from_array(out))
}

///|
fn hex_digit(byte : Byte) -> Int32? {
  match byte {
    b'0'..<=b'9' => Some(byte.to_int() - b'0'.to_int())
    b'a'..<=b'f' => Some(byte.to_int() - b'a'.to_int() + 10)
    b'A'..<=b'F' => Some(byte.to_int() - b'A'.to_int() + 10)
    _ => None
  }
}

///|
/// The rules of the settings and of the variables of the shell. `login` is the one of the
/// setting `download.proxy_login`, and `direct` is `download.no_proxy`. The settings win.
///
/// `NO_PROXY` is for all programs, so it can have entries that the command does not know, such
/// as a network. The command ignores these.
pub fn ProxyRules::ProxyRules(
  choice : ProxyChoice,
  env_vars : Map[String, String],
  login? : ProxyLogin,
  direct? : ArrayView[HostRule],
) -> ProxyRules raise ProxyVariableError {
  let proxy = match choice {
    NoProxy => None
    Use(address) => Some(Proxy::{ address, login, })
    FromVariables =>
      match variable(env_vars, ["HTTPS_PROXY", "ALL_PROXY"]) {
        None => None
        Some((name, text)) => {
          let (address, own) = proxy_parts(text) catch {
            error => raise WrongProxyVariable(variable=name, error)
          }
          let own = own.map(text => {
            // A user name without a password has an empty one.
            let text = percent_decoded(
              if text.contains(":") {
                text
              } else {
                "\{text}:"
              },
            )
            Some(ProxyLogin::parse(text)) catch {
              _ => None
            }
          })
          let login = match (login, own) {
            (Some(_), _) => login
            (None, Some(own)) => own
            (None, None) => None
          }
          Some({ address, login, })
        }
      }
  }
  let direct = match direct {
    Some(rules) => rules.iter().collect()
    None =>
      match variable(env_vars, ["NO_PROXY"]) {
        None => []
        Some((_, text)) =>
          text
          .replace_all(old=" ", new=",")
          .split(",")
          .filter_map(entry => {
            let rule = Some(HostRule::parse(entry.trim().to_owned())) catch {
              _ => None
            }
            rule
          })
          .collect()
      }
  }
  { proxy, direct: ReadOnlyArray::from_array(direct), }
}

///|
/// The proxy for a connection to this host. `None` is a connection without a proxy. A
/// connection to this machine has none, because the proxy would connect to its own machine.
pub fn ProxyRules::proxy_for(self : ProxyRules, host : HostName) -> Proxy? {
  guard !host.is_loopback() &&
    !self.direct.iter().any(rule => rule.matches(host)) else {
    None
  }
  self.proxy
}

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

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

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

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

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

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

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

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