use std::os::windows::process::CommandExt;
use std::process::Command;

const CREATE_NO_WINDOW: u32 = 0x08000000;
// const DETACHED_PROCESS: u32 = 0x00000008;

pub fn kill(name: &str) -> String {
    Command::new("taskkill")
        .args(&["/IM", name, "/F"])
        .creation_flags(CREATE_NO_WINDOW)
        .output()
        .unwrap();

    format!("Killing {}", name)
}

pub fn run_steam() -> std::io::Result<std::process::Output> {
    Command::new("cmd")
        .args(&["/C", "start", "steam://run"])
        .creation_flags(CREATE_NO_WINDOW)
        .output()
}


pub fn get_exe_path(name: &str) -> Result<String, std::io::Error> {
    // [原理]
    // Powershell 运行 Get-Process name | Select-Object path
    // 有name.exe运行时返回
    // Path
    // ----
    // 进程路径
    let command = format!("Get-Process {} | Select-Object path", name);
    let args = command.split_whitespace().collect::<Vec<&str>>();
    let output = Command::new("powershell.exe")
        .args(&args)
        .creation_flags(CREATE_NO_WINDOW)
        .output()?;

    let out = String::from_utf8_lossy(&output.stdout).to_string();

    if out.contains("Path") {
        let out = out.trim();
        let spt: Vec<&str> = out.split("\r\n").collect();

        if spt.len() > 2 {
            return Ok(spt[2].to_string());
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::Other,
        "Failed to get executable path",
    ))
}

pub fn open_path(path: &str) -> Result<(), std::io::Error> {
    // path中所有/ 转换为 \
    let path = path.replace("/", "\\");
    Command::new("cmd.exe")
        .args(["/c", "start", "", &path])
        .creation_flags(CREATE_NO_WINDOW)
        .spawn()
        .unwrap();
    Ok(())
}

mod tests {
    use super::*;
    #[test]
    fn test_open_path() {
        let path = "D:\\Programs\\Steam";
        println!("test open path: {}", path);
        open_path(path).unwrap();

        let path = "D:\\Programs\\Steam\\steamapps\\common\\Counter-Strike Global Offensive\\game\\bin\\win64";
        println!("test open path: {}", path);
        open_path(path).unwrap();

        let path = "%appdata%/Wmpvp/demo";
        println!("test open path: {}", path);
        open_path(path).unwrap()
    }

    #[test]
    fn test_get_exe_path() {
        let path = get_exe_path("steam").expect("failed");
        println!("test get steam path: {}", path);

        get_exe_path("not_running").expect("failed");
    }
}
