//! App launching on `Forge`: querying the crustace launcher and spawning the
//! first available candidate from a list.

use super::*;

impl Forge {
    pub(super) fn send_launcher_query(query: &str) {
        let escaped = query.replace('\\', "\\\\").replace('"', "\\\"");
        Self::send_to_crustace(&format!(
            r#"{{"action":"launcher_search_open","query":"{}"}}"#, escaped
        ));
    }

    pub(super) fn launch_first(candidates: &[&str], kind: &str) {
        let empty: [&str; 0] = [];
        for &prog in candidates {
            match daemon(prog, empty) {
                Ok(()) => {
                    info!("{kind}: launched {prog}");
                    return;
                },
                Err(_) => continue,
            }
        }
        // Try common Flatpak IDs as last resort
        let flatpak_ids: &[&str] = match kind {
            "Terminal" => &[
                "org.gnome.Ptyxis",
                "org.gnome.Terminal",
                "org.kde.konsole",
            ],
            "File manager" => &[
                "org.gnome.Nautilus",
                "org.gnome.Files",
                "org.kde.dolphin",
            ],
            "Browser" => &[
                "org.mozilla.firefox",
                "org.chromium.Chromium",
                "com.google.Chrome",
                "org.gnome.Epiphany",
            ],
            _ => &[],
        };
        for id in flatpak_ids {
            if daemon("flatpak", ["run", id]).is_ok() {
                info!("{kind}: launched flatpak {id}");
                return;
            }
        }
        error!("{kind} launch failed: no candidate found");
    }
}
