use std::{
    sync::atomic::{AtomicBool, Ordering},
    thread,
    time::Duration,
};

use pcsc_mon::PcscMonitor;

static RUNNING: AtomicBool = AtomicBool::new(true);

fn main() -> anyhow::Result<()> {
    let mut monitor = PcscMonitor::instance();
    monitor.on_card_inserted(|_ctx, card| {
        let mut buf: [u8; 2048] = [0; 2048];
        match card.get_attribute(pcsc::Attribute::AtrString, &mut buf) {
            Ok(atr) => println!("Card ATR: {:02X?}", atr),
            Err(err) => eprintln!("Failed to read ATR: {:?}", err),
        }
    });
    monitor.on_card_removed(move |reader| {
        println!("Card removed from reader: {}", reader);
    });
    monitor.on_reader_added(move |reader| {
        println!("Reader added: {}", reader);
    });
    monitor.on_reader_removed(move |reader| {
        println!("Reader removed: {}", reader);
    });
    monitor.on_error(move |e| {
        eprintln!("{:?}", e);
    });
    monitor.start();

    let _ = ctrlc::set_handler(|| {
        RUNNING.store(false, Ordering::SeqCst);
    });

    eprintln!("pcsc-monitor running… press Ctrl+C to quit.");
    while RUNNING.load(Ordering::SeqCst) {
        thread::sleep(Duration::from_millis(200));
    }

    Ok(())
    // If you have a graceful stop API, call it here:
    // m.stop();
}
