use std::fs;
use std::time::Instant;

const PATH: &str = "/usr/share/applications/";

fn read(path: &str) -> std::io::Result<()> {
    let files = fs::read_dir(path)?;
    for file in files {
        let file = file?;
        let path = file.path();
        let extension = path.extension().expect("error");

        if extension != "desktop" {
            continue;
        }

        let mut class: &str = "";
        let mut name: &str = "";
        let mut icon: &str = "";

        let file = fs::read_to_string(path)?;

        for line in file.lines() {
            match line {
                line if line.starts_with("StartupWMClass") => {
                    class = match line.split_once('=') {
                        Some((_, class)) => class,
                        None => "",
                    }
                }
                line if line.starts_with("Name") => {
                    name = match line.split_once('=') {
                        Some((_, name)) => name,
                        None => "",
                    }
                }
                line if line.starts_with("Icon") => {
                    icon = match line.split_once('=') {
                        Some((_, icon)) => icon,
                        None => "",
                    }
                }
                _ => (),
            }
        }
        println!("Class: {class}, Name: {name}, Icon: {icon}");
    }

    Ok(())
}

fn main() {
    let start_time = Instant::now();
    read(PATH).expect("error");
    let end_time = Instant::now();

    let time = end_time - start_time;

    println!(
        "Time taken: {}.{:03}s",
        time.as_secs(),
        time.subsec_millis()
    );
}
