#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

// 标准库
use std::collections::BTreeMap;
use std::process::Command;

// 系统信息库
use sysinfo::{DiskExt, System, SystemExt};
// 异步编程库: https://github.com/tokio-rs/tokio
use tokio::time::{self, Duration};
// 时间函数库: https://github.com/chronotope/chrono
// use chrono::prelude::*;
// JSON 序列化库
// use serde::{Deserialize, Serialize};

fn find() -> BTreeMap<String, String> {
    let system = System::new_all();
    let mut devices: BTreeMap<String, String> = BTreeMap::new();
    for disk in system.disks() {
        let point = disk
            .mount_point()
            .to_str()
            .map(str::to_string)
            .clone()
            .unwrap();
        let name = disk.name().to_str().map(str::to_string).clone().unwrap();
        devices.insert(point, name);
    }

    return devices;
}

async fn loop_find(mut devices: BTreeMap<String, String>) {
    let mut interval = time::interval(Duration::from_millis(500));

    println!("");
    println!("===========================================");
    println!("{:?}", devices);
    println!("===========================================");
    println!("");

    loop {
        interval.tick().await;

        let latest_devices = find();
        let size = devices.len();
        let latest_size = latest_devices.len();

        if size != latest_size {
            for (k, v) in &latest_devices {
                if !devices.contains_key(k) {
                    println!("attach: {:?}, {:?}", v, k);

                    // 打开文件夹
                    Command::new("EXPLORER").arg(k).spawn().unwrap();
                }
            }

            for (k, v) in &devices {
                if !latest_devices.contains_key(k) {
                    println!("detach: {:?}, {:?}", v, k);
                }
            }

            devices = latest_devices;
        }
    }
}

fn main() {
    tauri::Builder::default()
        .setup(|_app| {
            // let app_handle = app.handle();

            let devices = find();

            tauri::async_runtime::spawn(async move {
                // A loop that takes output from the async process and sends it
                // to the webview via a Tauri Event
                loop_find(devices).await
            });

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
