use ahash::AHashMap;
use std::collections::VecDeque;

use crate::DeviceSpec;

/// Lightweight FIFO in-memory cache.
#[derive(Debug)]
pub(crate) struct MemCache {
    pub(crate) map: AHashMap<String, DeviceSpec>,
    pub(crate) order: VecDeque<String>,
    pub(crate) capacity: usize,
}

impl MemCache {
    pub(crate) fn new(capacity: usize) -> Self {
        Self {
            map: AHashMap::with_capacity(capacity),
            order: VecDeque::with_capacity(capacity),
            capacity,
        }
    }

    pub(crate) fn insert(&mut self, key: String, value: DeviceSpec) {
        if self.map.contains_key(&key) {
            return;
        }
        if self.map.len() >= self.capacity
            && let Some(oldest) = self.order.pop_front()
        {
            self.map.remove(&oldest);
        }
        self.map.insert(key.clone(), value);
        self.order.push_back(key);
    }
}
