use std::path::Path;

pub struct KeyboardLockStates {
    pub(crate) caps_lock: bool,
    pub(crate) num_lock: bool,
    pub(crate) scroll_lock: bool,
}

impl KeyboardLockStates {
    pub(crate) fn get_locks_state() -> Option<KeyboardLockStates> {
        let leds_dir = Path::new("/sys/class/leds/");

        let mut caps_lock = false;
        let mut num_lock = false;
        let mut scroll_lock = false;

        let entries = std::fs::read_dir(leds_dir).ok()?;

        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_lowercase();

            if !caps_lock && name.contains("capslock") {
                caps_lock = is_led_enabled(&entry.path());
            } else if !num_lock && name.contains("numlock") {
                num_lock = is_led_enabled(&entry.path());
            } else if !scroll_lock && name.contains("scrolllock") {
                scroll_lock = is_led_enabled(&entry.path());
            }

            if caps_lock && num_lock && scroll_lock {
                break;
            }
        }

        Some(KeyboardLockStates {
            caps_lock,
            num_lock,
            scroll_lock,
        })
    }
}

fn is_led_enabled(led_path: &Path) -> bool {
    let brightness_path = led_path.join("brightness");

    std::fs::read_to_string(brightness_path)
        .is_ok_and(|content| content.trim() != "0")
}