nmwrap 0.1.0

An interactive terminal user interface (TUI) written in Rust and Ratatui for scanning and managing Wi-Fi connections using nmcli
use std::{
    fs::{self, OpenOptions},
    io::{self, Read, Write},
};

pub fn read_wifi_list_cache() -> Vec<String> {
    let mut result = Vec::new();
    if let Some(mut home) = std::env::home_dir() {
        home.push(".cache/nmwrap/nmwrap.txt");
        let file = OpenOptions::new().read(true).open(&home);

        match file {
            Ok(mut file) => {
                let mut buffer = String::new();
                if file.read_to_string(&mut buffer).is_err() {
                    return Vec::new();
                }
                for names in buffer.lines() {
                    result.push(names.to_owned());
                }
                return result;
            }
            Err(_) => return result,
        }
    }
    result
}

#[allow(unused)]
pub fn add_wifi_list_cache(wifi: &str) -> io::Result<()> {
    if let Some(mut home) = std::env::home_dir() {
        home.push(".cache/nmwrap");
        fs::create_dir_all(&home)?;

        let cache_file = home.join("nmwrap.txt");
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .read(true)
            .open(cache_file)?;

        let mut buffer = String::new();
        file.read_to_string(&mut buffer)?;

        if buffer.lines().any(|x| x == wifi) {
            return Ok(());
        }

        writeln!(file, "{wifi}")?;
    }
    Ok(())
}

#[allow(unused)]
pub fn delete_wifi_list_cache(wifi: &str) -> io::Result<()> {
    if let Some(mut home) = std::env::home_dir() {
        home.push(".cache/nmwrap");
        fs::create_dir_all(&home)?;

        let cache_file = home.join("nmwrap.txt");
        let mut file_read = OpenOptions::new().read(true).open(&cache_file)?;

        let mut buffer = String::new();
        file_read.read_to_string(&mut buffer)?;

        let mut file_write = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&cache_file)?;

        let mut wifi_container = String::new();
        for i in buffer.lines() {
            if i.trim() == wifi.trim() {
                continue;
            }
            wifi_container.push_str(format!("{}\n", i).as_str());
        }

        wifi_container.pop();
        if !(wifi_container == "\n" || wifi_container.lines().all(|f| f == " ")) {
            writeln!(file_write, "{wifi_container}")?;
        }
    }
    Ok(())
}

#[test]
fn test_write_wifi() {
    // add_wifi_list_cache("pop").unwrap();
    // delete_wifi_list_cache("lawak").unwrap();
    let test = read_wifi_list_cache();
    println!("{test:?}");
}