use ql_core::err;

use crate::search::kill_proc;

pub fn search_for_window(pid: u32, sys: &sysinfo::System) -> bool {
    if which::which("xdotool").is_err() {
        err!("xdotool isn't installed! Please install it first.");
        std::process::exit(1);
    }

    if which::which("xrandr").is_err() {
        err!("xrandr isn't installed! The game might break without it");
    }

    match duct::cmd("xdotool", &["search", "--pid", pid.to_string().as_str()])
        .stdout_capture()
        .run()
    {
        Ok(n) => {
            if kill_process(pid, sys, n) {
                println!();
                return true;
            }
        }

        Err(_) => match duct::cmd("xdotool", ["search", "--classname", "Minecraft*"])
            .stdout_capture()
            .run()
        {
            Ok(n) => {
                if kill_process(pid, sys, n) {
                    println!();
                    return true;
                }
            }
            Err(err) if err.to_string().contains("exited with code") => {}
            Err(err) => {
                err!("{err:?}");
            }
        },
    }
    false
}

fn kill_process(pid: u32, sys: &sysinfo::System, n: std::process::Output) -> bool {
    if String::from_utf8_lossy(&n.stdout)
        .lines()
        .map(|n| n.trim())
        .any(|n| !n.is_empty())
    {
        if kill_proc(pid, sys) {
            return true;
        }
    }
    false
}
