//! # Administrators key authentication challenges helper
//!
//! Allows to temporarily stores keys authentication challenges
//!
//! @author Pierre Hubert

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use webauthn_rs::AuthenticationState;

use crate::data::error::Res;

static mut CACHE: Option<Arc<Mutex<HashMap<u64, AuthenticationState>>>> = None;

/// Initialize this helper's cache
pub fn init() {
    unsafe {
        let map = HashMap::new();
        CACHE = Some(Arc::new(Mutex::new(map)));
    }
}

/// Store a new entry in the cache
pub fn set(key_id: u64, state: AuthenticationState) -> Res {
    let cache = unsafe {
        CACHE.as_ref().unwrap().lock()
    };

    cache?.insert(key_id, state);

    Ok(())
}

pub fn get(key_id: u64) -> Res<Option<AuthenticationState>> {
    let cache = unsafe {
        CACHE.as_ref().unwrap().lock()
    };

    Ok(cache?.remove(&key_id))
}