use std::{
    env,
    process::Command,
};

pub fn get_temperature() -> f32 {

    let mut temperature = 0.0;
    let system = env::var("SYSTEM").unwrap().to_string();

    if system == "ubuntu" {
        let temperature_command = Command::new("cat")
            .arg("/sys/class/thermal/thermal_zone1/temp")
            .output().unwrap_or_else(|e| {
                panic!("failed to execute process: {}", e)
        });

        let temperature_string = &String::from_utf8_lossy(&temperature_command.stdout)[..5];
        temperature = temperature_string.parse::<f32>().unwrap();
        temperature = temperature / 1000.0;
    } else {
        let temperature_command = Command::new("sudo")
            .arg("/opt/vc/bin/vcgencmd")
            .arg("measure_temp")
            .output().unwrap_or_else(|e| {
                panic!("failed to execute process: {}", e)
        });

        let mut temperature_string = &String::from_utf8_lossy(&temperature_command.stdout)[5..];
        temperature_string = &temperature_string[..temperature_string.len() - 3];
        temperature += temperature_string.parse::<f32>().unwrap();
    }

    return temperature;
}

pub fn get_storage() -> i8 {
    let storage_command = Command::new("df")
        .arg("-h")
        .arg("/")
        .output().unwrap_or_else(|e| {
            panic!("failed to execute process: {}", e)
        });

    let storage_string = &String::from_utf8_lossy(&storage_command.stdout);
    let vec_storage : Vec<&str> = storage_string.split_whitespace().collect();
    let storage = (vec_storage[vec_storage.len() - 2][..2]).parse::<i8>().unwrap();

    return storage;
}

pub fn get_mem() -> i8 {
    let mem_command = Command::new("free")
    .arg("-m")
    .output().unwrap_or_else(|e| {
        panic!("failed to execute process: {}", e)
    });

    let mem_string = &String::from_utf8_lossy(&mem_command.stdout);
    let vec_mem : Vec<&str> = mem_string.split_whitespace().collect();
    let total =  vec_mem[7].parse::<f32>().unwrap();
    let mem_use =  vec_mem[8].parse::<f32>().unwrap();
    let result = (mem_use / total * 100.0) as i8;

    return result;
}

pub fn get_battery() -> i8 {
    let system = env::var("SYSTEM").unwrap().to_string();
    let mut battery = 0;

    if system == "ubuntu" {
        let battery_command = Command::new("cat")
        .arg("/sys/class/power_supply/BAT0/capacity")
        .output().unwrap_or_else(|e| {
            panic!("failed to execute process: {}", e)
        });

        let battery_string = &String::from_utf8_lossy(&battery_command.stdout);
        battery = (&battery_string[..battery_string.len() - 1]).parse::<i8>().unwrap();
    }

    return battery;
}
