// Steam metadata parsing from reg, including:
// - Steam Path
// - Users (ID32)
#![allow(unused)]
use crate::tool::common::kill;
use crate::tool::common::run_steam;
use std::process::Command;

#[cfg(target_os = "windows")]
use winreg::enums::*;
#[cfg(target_os = "windows")]
use winreg::RegKey;
#[cfg(target_os = "windows")]
static STEAM_REG: &str = r"Software\Valve\Steam";

#[derive(Debug)]
pub struct SteamReg {
    pub steam_path: String,
    pub auto_login_user: String,
    pub suppress_auto_run: u32,
    pub remember_password: u32,
    pub language: String,
    pub users: Vec<String>,
}

impl SteamReg {
    #[cfg(target_os = "windows")]
    pub fn get_all<'a>() -> Result<Self, &'a str> {
        let hkcu = RegKey::predef(HKEY_CURRENT_USER);
        let cur_ver = hkcu.open_subkey(STEAM_REG).expect("steam reg");

        let steam_path: String = cur_ver.get_value("SteamExe").expect("steam path");
        let auto_login_user: String = cur_ver.get_value("AutoLoginUser").expect("auto login user");
        let suppress_auto_run: u32 = cur_ver
            .get_value("SuppressAutoRun")
            .expect("suppress auto run");
        let remember_password: u32 = cur_ver
            .get_value("RememberPassword")
            .expect("remember password");
        let language: String = cur_ver.get_value("Language").expect("language");

        let users = cur_ver
            .open_subkey("Users")
            .expect("users")
            .enum_keys()
            .map(|x| x.unwrap().to_string())
            .collect::<Vec<String>>();

        Ok(Self {
            steam_path,
            auto_login_user,
            suppress_auto_run,
            remember_password,
            language,
            users: users,
        })
    }
}

#[cfg(target_os = "windows")]
pub fn set_auto_login_user(user: &str) -> Result<(), &str> {
    // ensure steam.exe is not running
    kill("steam.exe");

    // set reg key value
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let cur_ver = hkcu
        .open_subkey_with_flags(STEAM_REG, KEY_WRITE)
        .expect("steam reg");

    cur_ver
        .set_value("AutoLoginUser", &user)
        .expect("auto login user");
    cur_ver
        .set_value("RememberPassword", &1u32)
        .expect("remember passwd");

    // open steam.exe again
    let output = run_steam().expect("failed to execute process");

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(target_os = "windows")]
    fn test_get_steam_path() {
        let path = SteamReg::get_all().unwrap();
        println!("{:?}", path);
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn test_set_auto_login() {
        // set_auto_login_user("_im_ai_");
        set_auto_login_user("_jerry_dota2");
    }
}
