///|
/// The commands that open a link in the browser, in the order to try them. Gives
/// `Skipped` when no browser can open on the machine of the user.
///
/// In an SSH session the browser would open on the other machine. The `BROWSER` variable
/// does not change this.
fn browser_commands(
  platform : @types.Platform,
  link : String,
  env_vars : Map[String, String],
) -> Result[Array[Array[String]], @command.BrowserOutcome] {
  let is_set = name => env_vars.get(name) is Some(value) && !value.is_blank()
  if is_set("SSH_CONNECTION") || is_set("SSH_TTY") {
    return Err(Skipped("an SSH session"))
  }
  match @open_in_browser.commands(platform, link, env=env_vars) {
    Ok([]) => Err(NotOpened("there is no command for the browser"))
    Ok(commands) => Ok(commands)
    // The only other reason of the package.
    Err(_) => Err(Skipped("a machine without a display"))
  }
}

///|
/// Tries the commands until `launch` starts one. `launch` gives the reason when a
/// command does not start.
async fn open_with(
  commands : Array[Array[String]],
  launch : async (Array[String]) -> Result[Unit, String] noraise,
) -> @command.BrowserOutcome noraise {
  let reasons = []
  for command in commands {
    match launch(command) {
      Ok(_) => return Opened
      Err(reason) => reasons.push(reason)
    }
  }
  NotOpened(reasons.join(", "))
}

///|
/// The full path of the program of a browser command, or the reason when there is none.
/// A path that is not absolute is for the working directory, so it gives no program.
async fn browser_program(
  name : String,
  env_vars : Map[String, String],
  platform : @core.Platform,
) -> Result[String, String] noraise {
  let absolute = text => {
    Some(@core.FolderPath::FolderPath(text, platform).to_string()) catch {
      _ => None
    }
  }
  // The default command of Windows. It is a part of the system.
  if platform is Windows && name == "rundll32" {
    return match windows_variable(env_vars, "SystemRoot").bind(absolute) {
      Some(folder) => Ok("\{folder}\\System32\\rundll32.exe")
      None => Err("the environment variable SystemRoot has no absolute path")
    }
  }
  let is_path = name.contains("/") ||
    (platform is Windows && (name.contains("\\") || name.contains(":")))
  let program = if is_path {
    absolute(name)
  } else {
    find_program(name, path_folders(env_vars, platform), platform)
  }
  match program {
    Some(program) => Ok(program)
    None => Err("\{name} is not installed")
  }
}

///|
/// Starts a program that continues after this one, and gives its ID. `program` is a full
/// path. No window of a terminal opens, and the program has no file and no pipe of this
/// one, so it writes nothing to the terminal. Without a folder, it has the working
/// directory of this program.
async fn spawn_silent(
  program : String,
  args : ArrayView[String],
  folder : String?,
) -> Int32 {
  let null_device = match @async.platform {
    Windows => "NUL"
    Linux | MacOS => "/dev/null"
  }
  let input = @process.redirect_from_file(null_device)
  let output = @process.redirect_to_file(null_device)
  @process.spawn_orphan(
    program,
    args,
    stdin=input,
    stdout=output,
    stderr=output,
    cwd?=folder.map(path => path[:]),
    no_console_window=true,
  )
}

///|
/// How long a browser command has to fail, in milliseconds. `xdg-open` ends at once when
/// there is no browser, and it can run until the browser ends.
let browser_limit : Int32 = 1000

///|
/// Starts a browser command. No window of a terminal opens, the browser writes nothing
/// to the terminal, and it does not have the working directory of the user, because on
/// Windows nobody could delete that folder then. The browser continues after this
/// program.
async fn launch_browser(
  command : Array[String],
  folder : String?,
  env_vars : Map[String, String],
  platform : @core.Platform,
) -> Result[Unit, String] noraise {
  let name = command[0]
  let program = match browser_program(name, env_vars, platform) {
    Ok(program) => program
    Err(reason) => return Err(reason)
  }
  try {
    let pid = spawn_silent(program, command[1:], folder)
    match @async.platform {
      // The start of a program that is not there fails on Windows. The exit code of
      // `rundll32` says nothing.
      Windows => None
      // `explorer.exe` ends with 1 after a success.
      Linux | MacOS if name == "explorer.exe" => None
      Linux | MacOS =>
        @async.with_timeout_opt(browser_limit, () => @process.wait_pid(pid))
    }
  } catch {
    @os_error.OSError(_) as error if error.is_ENOENT() =>
      Err("\{name} is not installed")
    error => Err("\{name} does not start: \{error}")
  } noraise {
    None | Some(0) => Ok(())
    Some(code) => Err("\{name} ended with the code \{code}")
  }
}