///|
/// The name of the file next to 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 next to 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 next to the app, from the complete path of its program. On macOS
/// the app is the bundle `NAME.app`, which contains the program.
///
/// `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 = above(program)
  let contents = above(folder)
  let bundle = above(contents)
  let app = if platform is MacOs &&
    folder.name() == "MacOS" &&
    contents.name() == "Contents" &&
    bundle.name().has_suffix(".app") {
    bundle
  } else {
    program
  }
  from(above(app), installed_instance_file)
}

///|
/// 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}