use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported


use std::thread::sleep;
use std::time::Duration;
use std::fs::{File, read_dir};
use std::io::prelude::*;
use std::ffi::{CString, CStr};
use std::path::Path;

fn main() {
    esp_idf_sys::link_patches();
    println!("Hello, world!");

    

    let mount_config = esp_idf_sys::esp_vfs_fat_mount_config_t {
        format_if_mount_failed: true,
        max_files: 4,
        allocation_unit_size: 4096,
    };
    let mut wl_handle = esp_idf_sys::WL_INVALID_HANDLE;
    let mount_path = CString::new("/spiflash").expect("CString::new failed");
    let mount_vol = CString::new("storage").expect("CString::new failed");
    let rt = unsafe {
        esp_idf_sys::esp_vfs_fat_spiflash_mount(
            mount_path.as_ptr(),
            mount_vol.as_ptr(),
            &mount_config,
            &mut wl_handle as *mut i32,
        )
    };

    // println!("\nMount result: {:?}", esp_idf_sys::EspError::from(rt));

    println!("{}", Path::new("/spiflash/demo.txt").exists());

    {
        let mut file = File::create("/spiflash/demo.txt").unwrap();
        file.write_all(b"abc").unwrap();
    }

    
    println!("{}", Path::new("/spiflash/demo.txt").exists());

    {
        let mut file = File::open("/spiflash/demo.txt").unwrap();
        let mut cxt = String::new();
        file.read_to_string(&mut cxt).unwrap();
        println!("Read: {}", cxt)
    }
}