///|
/// The system whose rules read a path and write the paths of its files.
#derive(Eq, Debug)
pub(all) enum Platform {
  Windows
  MacOs
  Linux
}

///|
/// Raised when a text is not an absolute folder path.
#derive(Eq, Debug)
pub(all) suberror FolderPathError {
  /// The text has no characters.
  EmptyPath
  /// The text is not an absolute path on the platform. On Windows this
  /// includes a path with a drive and no root (`C:a`), a path with a root and
  /// no drive (`\a`, for the constructor only), and a text with a malformed
  /// root: `\\server` without a share, a `\\?\` path that is not a drive or
  /// UNC path, a device path (`\\.\C:\a`) and a text with three leading
  /// separators.
  RelativePath(String)
}

///|
/// The absolute path of a folder, in one clean form: no `.` or `..` parts, no
/// repeated or trailing separators, and, on Windows, the separator `\` and an
/// upper-case drive letter.
///
/// `==` compares the clean text. Use `same_folder` to compare folders: on
/// Windows it ignores the case of letters.
#derive(Eq, Debug)
struct FolderPath {
  platform : Platform
  /// `/`, a drive such as `C:\`, or a share such as `\\server\share`.
  root : String
  /// The folder names after the root. A name has no separator.
  names : Array[String]
}

///|
fn is_separator(c : Char, platform : Platform) -> Bool {
  c == '/' || (platform == Windows && c == '\\')
}

///|
/// The parts of a text between separators. Empty parts are left out.
fn split_names(text : Iter[Char], platform : Platform) -> Array[String] {
  let names : Array[String] = []
  let current = StringBuilder()
  for c in text {
    if is_separator(c, platform) {
      if !current.is_empty() {
        names.push(current.to_string())
        current.reset()
      }
    } else {
      current.write_char(c)
    }
  }
  if !current.is_empty() {
    names.push(current.to_string())
  }
  names
}

///|
/// What the start of a text says about its root.
priv enum Rooted {
  /// A root and the text after it.
  Absolute(root~ : String, rest~ : Array[Char])
  /// Windows only: a separator and no drive. The base gives the drive.
  RootOnly(rest~ : Array[Char])
  /// Windows only: the text starts with two separators and has no valid root,
  /// such as `\\server`, `\\.\C:\a` or `\\?\Volume{x}\a`.
  Malformed
  Relative
}

///|
fn is_letter(c : Char) -> Bool {
  c is ('a'..<='z' | 'A'..<='Z')
}

///|
fn starts_with_unc(chars : ArrayView[Char]) -> Bool {
  chars.length() >= 4 &&
  chars[0] is ('U' | 'u') &&
  chars[1] is ('N' | 'n') &&
  chars[2] is ('C' | 'c') &&
  is_separator(chars[3], Windows)
}

///|
/// A root of the form `\\server\share`, from the text after the two separators.
/// One scan finds the root and the rest. A text with no server or no share is
/// `Malformed`.
fn unc_root(chars : ArrayView[Char]) -> Rooted {
  let names : Array[String] = []
  let current = StringBuilder()
  let mut index = 0
  while index < chars.length() {
    let c = chars[index]
    if is_separator(c, Windows) {
      if !current.is_empty() {
        names.push(current.to_string())
        current.reset()
      }
      if names.length() == 2 {
        break
      }
    } else {
      current.write_char(c)
    }
    index += 1
  }
  if !current.is_empty() {
    names.push(current.to_string())
  }
  guard names.length() == 2 else { return Malformed }
  Absolute(
    root="\\\\\{names[0]}\\\{names[1]}",
    rest=chars[index:].iter().collect(),
  )
}

///|
fn classify(text : String, platform : Platform) -> Rooted {
  let chars : Array[Char] = text.iter().collect()
  match platform {
    Windows => classify_windows(chars[:])
    MacOs | Linux =>
      if chars.length() > 0 && chars[0] == '/' {
        Absolute(root="/", rest=chars)
      } else {
        Relative
      }
  }
}

///|
fn classify_windows(chars : ArrayView[Char]) -> Rooted {
  let n = chars.length()
  let sep = c => is_separator(c, Windows)
  // `\\?\` is the verbatim prefix.
  if n >= 4 &&
    sep(chars[0]) &&
    sep(chars[1]) &&
    chars[2] == '?' &&
    sep(chars[3]) {
    let inner = chars[4:]
    if starts_with_unc(inner) {
      unc_root(inner[4:])
    } else {
      match classify_windows(inner) {
        Absolute(root~, rest~) if root.length() == 3 => Absolute(root~, rest~)
        _ => Malformed
      }
    }
  } else if n >= 4 &&
    sep(chars[0]) &&
    sep(chars[1]) &&
    chars[2] == '.' &&
    sep(chars[3]) {
    // A device path.
    Malformed
  } else if n >= 3 && sep(chars[0]) && sep(chars[1]) && sep(chars[2]) {
    Malformed
  } else if n >= 2 && sep(chars[0]) && sep(chars[1]) {
    unc_root(chars[2:])
  } else if n >= 1 && sep(chars[0]) {
    RootOnly(rest=chars.iter().collect())
  } else if n >= 3 && is_letter(chars[0]) && chars[1] == ':' && sep(chars[2]) {
    Absolute(
      root=chars[0].to_ascii_uppercase().to_string() + ":\\",
      rest=chars[3:].iter().collect(),
    )
  } else {
    Relative
  }
}

///|
/// Adds names to a list of names: `.` stays out and `..` removes the last name.
/// A `..` at the root stays at the root.
fn fold_names(start : Array[String], more : Array[String]) -> Array[String] {
  let names = start.copy()
  for name in more {
    match name {
      "." => ()
      ".." => ignore(names.pop())
      _ => names.push(name)
    }
  }
  names
}

///|
/// The path in a text of a person. "Copy as path" in the Windows Explorer gives a path
/// in double quotes, and no name on Windows can have a quote. So one pair around the
/// text is not a part of the path there.
fn unquoted(text : String, platform : Platform) -> String raise FolderPathError {
  let path = match (platform, text) {
    (Windows, ['"', .. path, '"']) => path.to_owned()
    _ => text
  }
  guard path != "" else { raise EmptyPath }
  path
}

///|
/// Parses an absolute folder path and makes it clean. On Windows, the text can have
/// one pair of double quotes around the path.
pub fn FolderPath::FolderPath(
  text : String,
  platform : Platform,
) -> FolderPath raise FolderPathError {
  let text = unquoted(text, platform)
  match classify(text, platform) {
    Absolute(root~, rest~) =>
      {
        platform,
        root,
        names: fold_names([], split_names(rest.iter(), platform)),
      }
    RootOnly(..) | Malformed | Relative => raise RelativePath(text)
  }
}

///|
/// Reads a path from a base folder. An absolute text gives its own folder and
/// ignores the base. A relative text starts at the base. On Windows, a text
/// with a root and no drive (`\a`) uses the drive or share of the base, and the
/// text can have one pair of double quotes around the path.
pub fn FolderPath::resolve(
  text : String,
  base : FolderPath,
) -> FolderPath raise FolderPathError {
  let platform = base.platform
  let text = unquoted(text, platform)
  match classify(text, platform) {
    Absolute(root~, rest~) =>
      {
        platform,
        root,
        names: fold_names([], split_names(rest.iter(), platform)),
      }
    Malformed => raise RelativePath(text)
    RootOnly(rest~) =>
      {
        platform,
        root: base.root,
        names: fold_names([], split_names(rest.iter(), platform)),
      }
    Relative =>
      // `C:a` is the folder `a` on the current folder of the drive `C`, which
      // a path text cannot say. Refuse it.
      if platform == Windows && has_drive_prefix(text) {
        raise RelativePath(text)
      } else {
        {
          platform,
          root: base.root,
          names: fold_names(base.names, split_names(text.iter(), platform)),
        }
      }
  }
}

///|
fn has_drive_prefix(text : String) -> Bool {
  let chars : Array[Char] = text.iter().take(2).collect()
  chars.length() == 2 && is_letter(chars[0]) && chars[1] == ':'
}

///|
fn FolderPath::separator(self : FolderPath) -> String {
  match self.platform {
    Windows => "\\"
    MacOs | Linux => "/"
  }
}

///|
/// The path with more folder names. Each name has no separator.
fn FolderPath::join(self : FolderPath, names : Array[String]) -> FolderPath {
  { ..self, names: self.names + names, }
}

///|
/// The clean text of the path.
pub fn FolderPath::to_string(self : FolderPath) -> String {
  if self.names.is_empty() {
    self.root
  } else if self.root.has_suffix("/") || self.root.has_suffix("\\") {
    self.root + self.names.join(self.separator())
  } else {
    self.root + self.separator() + self.names.join(self.separator())
  }
}

///|
/// The name of the folder. The root has its own text as its name.
pub fn FolderPath::name(self : FolderPath) -> String {
  match self.names.last() {
    Some(name) => name
    None => self.root
  }
}

///|
/// The name of the folder that holds this folder: the root text for a folder
/// at the top, and `None` for the root.
pub fn FolderPath::parent_name(self : FolderPath) -> String? {
  match self.names.length() {
    0 => None
    1 => Some(self.root)
    n => Some(self.names[n - 2])
  }
}

///|
fn FolderPath::key(self : FolderPath, text : String) -> String {
  match self.platform {
    Windows => text.to_lower()
    MacOs | Linux => text
  }
}

///|
/// True when `other` is this folder or is below it. A folder that has the
/// start of the name is not below it: `/code/docs` does not hold
/// `/code/docs-old`. The paths of two platforms never hold each other.
pub fn FolderPath::contains(self : FolderPath, other : FolderPath) -> Bool {
  guard self.platform == other.platform else { return false }
  guard self.key(self.root) == self.key(other.root) else { return false }
  guard other.names.length() >= self.names.length() else { return false }
  for i, name in self.names {
    if self.key(name) != self.key(other.names[i]) {
      return false
    }
  }
  true
}

///|
/// True when both paths are one folder. Windows ignores the case of letters.
/// Linux and macOS compare the exact text.
pub fn FolderPath::same_folder(self : FolderPath, other : FolderPath) -> Bool {
  self.contains(other) && other.contains(self)
}

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

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