///|
/// The name of the file of an installed app that has the name of its instance.
pub let installed_instance_file : String = "mission-control-instance.txt"

///|
/// Raised when the app cannot know its instance from the variable or the file.
#derive(Eq, Debug)
pub(all) suberror InstanceError {
  InVariable(@app.InstanceNameError)
  InFile(path~ : @core.FolderPath, @app.InstanceNameError)
  /// The file is there, but the app cannot read it. The reason is for people.
  FileNotReadable(path~ : @core.FolderPath, reason~ : String)
}

///|
/// The environment variable with the name of the instance.
let instance_variable : String = "MISSION_CONTROL_INSTANCE"

///|
/// Reads the text of the file of an installed app: the name of its instance in one
/// line. Spaces around the name and the end of the line do not count.
pub fn installed_instance(
  text : String,
) -> @app.InstanceName raise @app.InstanceNameError {
  @app.InstanceName::InstanceName(text.trim().to_owned())
}

///|
/// The path of the file with the name of the instance, from the complete path of the
/// program. It is next to the program, or on macOS in the folder `Resources` of the bundle
/// `NAME.app`, because the folder `Applications` can have the apps of more instances.
///
/// `FolderPath` has the rules for the path of each file also.
pub fn installed_instance_path(
  program : @core.FolderPath,
  platform : @core.Platform,
) -> @core.FolderPath {
  let folder = match bundle_contents(program, platform) {
    Some(contents) => from(contents, "Resources")
    None => above(program)
  }
  from(folder, installed_instance_file)
}

///|
/// The folder `Contents` of the bundle `NAME.app` that contains the program. There is none
/// for a program that is not in a bundle of macOS.
pub fn bundle_contents(
  program : @core.FolderPath,
  platform : @core.Platform,
) -> @core.FolderPath? {
  let folder = above(program)
  let contents = above(folder)
  guard platform is MacOs &&
    folder.name() == "MacOS" &&
    contents.name() == "Contents" &&
    above(contents).name().has_suffix(".app") else {
    None
  }
  Some(contents)
}

///|
/// The variable with the path of the program that Proton starts for each helper.
pub let subprocess_variable : String = "PROTON_SUBPROCESS_PATH"

///|
/// The path of the helper of Proton in a bundle of macOS. `names` are the names in the
/// folder `Contents/Frameworks`.
///
/// Proton makes this path from the file name of the bundle, so a bundle with another name
/// does not open. The helper has no suffix, such as ` (GPU)`.
pub fn bundle_helper(
  contents : @core.FolderPath,
  names : ArrayView[String],
) -> @core.FolderPath? {
  let helpers = names
    .iter()
    .filter(name => name.has_suffix(" Helper.app"))
    .collect()
  guard helpers is [name] else { None }
  let program = name[:name.length() - ".app".length()].to_owned()
  Some(from(contents, "Frameworks/\{name}/Contents/MacOS/\{program}"))
}

///|
/// The folder that contains the path. The root contains itself.
fn above(path : @core.FolderPath) -> @core.FolderPath {
  from(path, "..")
}

///|
/// The path that a relative text gives from a folder.
fn from(folder : @core.FolderPath, relative : String) -> @core.FolderPath {
  // Only a text that is empty or has a root raises an error, and no caller has one.
  @core.FolderPath::resolve(relative, folder) catch {
    _ => folder
  }
}

///|
/// The instance that the user asks for: the one of the option, or else the one of the
/// variable `MISSION_CONTROL_INSTANCE`. An empty variable has no name. The option wins
/// over a variable that has a wrong value.
///
/// Without an answer, the app uses the instance of its file, or else the one of its
/// channel.
pub fn asked_instance(
  option : @app.InstanceName?,
  env_vars : Map[String, String],
) -> @app.InstanceName? raise InstanceError {
  guard option is None else { option }
  match env_vars.get(instance_variable) {
    None | Some("") => None
    Some(text) =>
      Some(@app.InstanceName::InstanceName(text)) catch {
        error => raise InVariable(error)
      }
  }
}

///|
/// The problem, as text for people.
pub fn InstanceError::message(self : InstanceError) -> String {
  match self {
    InVariable(error) =>
      "The environment variable \{instance_variable} has a wrong value. \{name_problem(error)}"
    InFile(path~, error) =>
      "The file \{path.to_string()} must have the name of the instance of this app. \{name_problem(error)}"
    FileNotReadable(path~, reason~) =>
      "The app cannot read the file \{path.to_string()}, which has the name of its instance. \{reason}"
  }
}

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

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