///|
/// The header layer: `Authorization` and `WWW-Authenticate` as HTTP writes
/// them, which is the part NTLM libraries usually leave to the caller.
///
/// A server may offer several schemes in one `WWW-Authenticate` header, and a
/// client picks one. Parameters are comma separated, except inside a quoted
/// string, so `Basic realm="a,b"` must not be split in the middle.
pub suberror HttpError {
  Malformed(String)
  EmptyToken
}

///|
pub struct Challenge {
  scheme : String
  token : Bytes
}

///|
pub fn Challenge::scheme(self : Challenge) -> String {
  self.scheme
}

///|
pub fn Challenge::token(self : Challenge) -> Bytes {
  self.token
}

///|
/// One code unit as a `Char`. Headers are ASCII in practice, but a string
/// from the network can hold a surrogate half — a four-byte UTF-8 character
/// split across two code units — and `to_char` returns `None` for those.
/// Unwrapping there would turn a malformed header into a panic, so the
/// replacement character stands in and simply fails every comparison.
fn char_at(text : String, at : Int) -> Char {
  match text[at].to_char() {
    Some(c) => c
    None => '\u{FFFD}'
  }
}

///|
fn is_blank(c : Char) -> Bool {
  let v = c.to_int()
  v == 32 || v == 9 || v == 10 || v == 13
}

///|
fn lower_code(v : Int) -> Int {
  if v >= 65 && v <= 90 {
    v + 32
  } else {
    v
  }
}

///|
fn substring(text : String, start : Int, end : Int) -> String {
  let out = StringBuilder()
  for i = start; i < end; i = i + 1 {
    out.write_char(char_at(text, i))
  }
  out.to_string()
}

///|
pub fn trim(text : String) -> String {
  let mut start = 0
  let mut end = text.length()
  while start < end && is_blank(char_at(text, start)) {
    start = start + 1
  }
  while end > start && is_blank(char_at(text, end - 1)) {
    end = end - 1
  }
  substring(text, start, end)
}

///|
fn same_scheme(text : String, name : String) -> Bool {
  if text.length() != name.length() {
    return false
  }
  let mut same = true
  for i = 0; i < text.length(); i = i + 1 {
    if lower_code(char_at(text, i).to_int()) !=
      lower_code(char_at(name, i).to_int()) {
      same = false
    }
  }
  same
}

///|
/// Split a header on commas that are outside quoted strings.
fn split_challenges(header : String) -> Array[String] {
  let parts : Array[String] = []
  let mut current = StringBuilder()
  let mut quoted = false
  for i = 0; i < header.length(); i = i + 1 {
    let c = char_at(header, i)
    if c == '"' {
      quoted = !quoted
      current.write_char(c)
    } else if c == ',' && !quoted {
      parts.push(trim(current.to_string()))
      current = StringBuilder()
    } else {
      current.write_char(c)
    }
  }
  let last = trim(current.to_string())
  if last.length() > 0 {
    parts.push(last)
  }
  parts
}

///|
fn decode_token(text : String) -> Bytes {
  @ntlm.token_from_header(text) catch {
    _ => b""
  }
}

///|
/// Every challenge in a `WWW-Authenticate` header, in the order offered.
pub fn parse_challenges(header : String) -> Array[Challenge] {
  let out : Array[Challenge] = []
  for part in split_challenges(header) {
    if part.length() == 0 {
      continue
    }
    let mut space = -1
    for i = 0; i < part.length(); i = i + 1 {
      if is_blank(char_at(part, i)) {
        space = i
        break
      }
    }
    let scheme = if space < 0 { part } else { substring(part, 0, space) }
    let rest = if space < 0 {
      ""
    } else {
      trim(substring(part, space, part.length()))
    }
    out.push({ scheme, token: decode_token(rest), })
  }
  out
}

///|
/// The scheme a client should prefer: SPNEGO first, then raw NTLM.
pub fn preferred(challenges : Array[Challenge]) -> Challenge? {
  let mut ntlm : Challenge? = None
  for challenge in challenges {
    if same_scheme(challenge.scheme(), "Negotiate") &&
      challenge.token().length() > 0 {
      return Some(challenge)
    }
    if same_scheme(challenge.scheme(), "NTLM") && challenge.token().length() > 0 {
      ntlm = Some(challenge)
    }
  }
  ntlm
}

///|
pub fn parse_authorization(header : String) -> Challenge raise {
  let text = trim(header)
  let mut space = -1
  for i = 0; i < text.length(); i = i + 1 {
    if is_blank(char_at(text, i)) {
      space = i
      break
    }
  }
  if space < 0 {
    raise Malformed("authorization header has no scheme")
  }
  let scheme = substring(text, 0, space)
  let rest = trim(substring(text, space, text.length()))
  if rest.length() == 0 {
    raise EmptyToken
  }
  { scheme, token: @ntlm.token_from_header(rest), }
}

///|
pub fn authorization_header(scheme : String, token : Bytes) -> String {
  scheme + " " + @ntlm.token_to_header(token)
}

///|
pub fn challenge_header(scheme : String) -> String {
  scheme
}

///|
pub fn challenge_header_with_token(scheme : String, token : Bytes) -> String {
  scheme + " " + @ntlm.token_to_header(token)
}