///|
/// Raised when the environment does not give a base folder.
#derive(Eq, Debug)
pub(all) suberror BaseFolderError {
  /// A variable that the platform needs is not set, or has an empty value.
  MissingVariable(String)
  /// The variable holds a path that is not absolute on the platform.
  NotAbsolute(variable~ : String, value~ : String)
}

///|
/// The folder that holds the folders of all instances.
#derive(Eq, Debug)
struct BaseFolder {
  folder : FolderPath
}

///|
/// The value of a variable. An empty value counts as not set.
fn lookup(env : Map[String, String], variable : String) -> String? {
  match env.get(variable) {
    Some("") | None => None
    found => found
  }
}

///|
fn absolute_from(
  platform : Platform,
  variable : String,
  value : String,
) -> FolderPath raise BaseFolderError {
  FolderPath::FolderPath(value, platform) catch {
    _ => raise NotAbsolute(variable~, value~)
  }
}

///|
fn is_absolute(value : String, platform : Platform) -> Bool {
  try FolderPath::FolderPath(value, platform) catch {
    _ => return false
  } noraise {
    _ => true
  }
}

///|
fn required(
  env : Map[String, String],
  variable : String,
) -> String raise BaseFolderError {
  match lookup(env, variable) {
    Some(value) => value
    None => raise MissingVariable(variable)
  }
}

///|
/// Finds the base folder from the environment. The caller reads the variables;
/// this function does no I/O.
///
/// `MISSION_CONTROL_HOME` wins over all other variables. Then Windows uses
/// `LOCALAPPDATA`, macOS uses `HOME`, and Linux uses `XDG_DATA_HOME` or
/// `HOME`. A variable with an empty value counts as not set. A relative
/// `XDG_DATA_HOME` is ignored, as the XDG standard says. Another variable with a
/// path that is not absolute raises `NotAbsolute`.
pub fn BaseFolder::of_env(
  platform : Platform,
  env : Map[String, String],
) -> BaseFolder raise BaseFolderError {
  let tail = ["moonrockz", "mission-control"]
  let folder = match lookup(env, "MISSION_CONTROL_HOME") {
    Some(value) => absolute_from(platform, "MISSION_CONTROL_HOME", value)
    None =>
      match platform {
        Windows =>
          absolute_from(platform, "LOCALAPPDATA", required(env, "LOCALAPPDATA")).join(
            tail,
          )
        MacOs =>
          absolute_from(platform, "HOME", required(env, "HOME")).join(
            ["Library", "Application Support"] + tail,
          )
        Linux => linux_data_folder(env).join(tail)
      }
  }
  { folder, }
}

///|
/// The folder for the data of the programs of a user on Linux: `XDG_DATA_HOME`, or
/// `.local/share` in the home folder. The application menu also reads it.
pub fn linux_data_folder(
  env : Map[String, String],
) -> FolderPath raise BaseFolderError {
  match lookup(env, "XDG_DATA_HOME") {
    // A relative value is ignored, as the XDG standard says.
    Some(value) if is_absolute(value, Linux) =>
      absolute_from(Linux, "XDG_DATA_HOME", value)
    _ =>
      absolute_from(Linux, "HOME", required(env, "HOME")).join([
        ".local", "share",
      ])
  }
}

///|
/// The text of the folder that holds one folder for each instance.
pub fn BaseFolder::instances(self : BaseFolder) -> String {
  self.folder.join(["instances"]).to_string()
}

///|
/// The folder of one instance.
pub fn BaseFolder::instance(
  self : BaseFolder,
  name : @app.InstanceName,
) -> InstanceFolder {
  { name, folder: self.folder.join(["instances", name.to_string()]), }
}

///|
/// The folder of one instance, and the paths of its four files.
#derive(Eq, Debug)
struct InstanceFolder {
  name : @app.InstanceName
  folder : FolderPath
}

///|
pub fn InstanceFolder::name(self : InstanceFolder) -> @app.InstanceName {
  self.name
}

///|
pub fn InstanceFolder::platform(self : InstanceFolder) -> Platform {
  self.folder.platform
}

///|
/// The text of the folder.
pub fn InstanceFolder::path(self : InstanceFolder) -> String {
  self.folder.to_string()
}

///|
/// `server.lock`: empty; the server holds a lock on it.
pub fn InstanceFolder::lock(self : InstanceFolder) -> String {
  self.folder.join(["server.lock"]).to_string()
}

///|
/// `server.json`: the port, the version and the secret of the server, or the
/// reason why it did not start.
pub fn InstanceFolder::record(self : InstanceFolder) -> String {
  self.folder.join(["server.json"]).to_string()
}

///|
/// `server.log`: the output of the background process.
pub fn InstanceFolder::log(self : InstanceFolder) -> String {
  self.folder.join(["server.log"]).to_string()
}

///|
/// `projects.json`: the project list.
pub fn InstanceFolder::projects(self : InstanceFolder) -> String {
  self.folder.join(["projects.json"]).to_string()
}

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

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

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

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