///|
/// The environment variable with the path of another desktop app.
pub let desktop_variable : String = "MISSION_CONTROL_DESKTOP"

///|
/// The folder of the desktop app that is installed for an instance.
pub fn BaseFolder::desktop(
  self : BaseFolder,
  name : @app.InstanceName,
) -> FolderPath {
  self.folder.join(["desktop", name.to_string()])
}

///|
/// The path of the program in a folder with an installed desktop app. The names are the
/// ones that Proton gives to the product `Mission Control Desktop`.
///
/// `FolderPath` has the rules for the path of each file also.
pub fn desktop_program(folder : FolderPath) -> FolderPath {
  match folder.platform {
    Windows => folder.join(["mission-control-desktop.exe"])
    MacOs => program_of_bundle(folder.join(["Mission Control Desktop.app"]))
    Linux => folder.join(["mission-control-desktop"])
  }
}

///|
/// The path of the program in a bundle of macOS.
fn program_of_bundle(bundle : FolderPath) -> FolderPath {
  bundle.join(["Contents", "MacOS", "mission-control-desktop"])
}

///|
/// The program that the variable `MISSION_CONTROL_DESKTOP` names, if its value is a
/// complete path. On macOS the path can be the one of a bundle.
fn named_program(env : Map[String, String], platform : Platform) -> FolderPath? {
  guard lookup(env, desktop_variable) is Some(text) else { None }
  let path = FolderPath::FolderPath(text, platform) catch { _ => return None }
  if platform is MacOs && path.name().has_suffix(".app") {
    Some(program_of_bundle(path))
  } else {
    Some(path)
  }
}

///|
/// The programs that can be the desktop app of an instance, in the order of the search:
/// the one of the variable `MISSION_CONTROL_DESKTOP`, the app that is installed for the
/// instance, and the app that is installed for the channel of the build. The caller looks
/// which of them is there.
///
/// Each path is complete, because the system looks for a name in the working directory
/// also. So the list does not have a relative path of the variable.
pub fn desktop_candidates(
  base : BaseFolder,
  name : @app.InstanceName,
  channel : @contracts.Channel,
  env : Map[String, String],
) -> ReadOnlyArray[FolderPath] {
  let programs = []
  if named_program(env, base.folder.platform) is Some(program) {
    programs.push(program)
  }
  for instance in [name, @app.InstanceName::of_channel(channel)] {
    let program = desktop_program(base.desktop(instance))
    if !programs.contains(program) {
      programs.push(program)
    }
  }
  ReadOnlyArray::from_array(programs)
}