use super::BatteryState;

pub fn get_battery_state() -> BatteryState {
    if let Some(path) = find_battery_path() {
        let percent = std::fs::read_to_string(path.join("capacity"))
            .ok()
            .and_then(|s| s.trim().parse::<u8>().ok())
            .unwrap_or(0);

        let status = std::fs::read_to_string(path.join("status"))
            .ok()
            .unwrap_or_default();

        let charging = {
            let st = status.trim();
            st.eq_ignore_ascii_case("charging") || st.eq_ignore_ascii_case("full")
        };

        let time_remaining = calculate_time_remaining(&path);

        BatteryState {
            percent,
            charging,
            time_remaining,
        }
    } else {
        BatteryState {
            percent: 0,
            charging: false,
            time_remaining: None,
        }
    }
}

/// Find the sysfs path for the battery (type == "Battery").
fn find_battery_path() -> Option<std::path::PathBuf> {
    for entry in std::fs::read_dir("/sys/class/power_supply").ok()?.flatten() {
        let path = entry.path();
        if let Ok(ptype) = std::fs::read_to_string(path.join("type")) {
            if ptype.trim() == "Battery" {
                return Some(path);
            }
        }
    }
    None
}

fn calculate_time_remaining(path: &std::path::Path) -> Option<u32> {
    let energy_now = std::fs::read_to_string(path.join("energy_now"))
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())?;

    let power_now = std::fs::read_to_string(path.join("power_now"))
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())?;

    if power_now > 0 {
        Some(((energy_now * 60) / power_now) as u32)
    } else {
        None
    }
}
