use crate::fact::MemoFact;
use std::collections::VecDeque;

const DEFAULT_CAPACITY: usize = 256;

pub struct ImmediateTrace {
    entries: VecDeque<MemoFact>,
    capacity: usize,
}

impl ImmediateTrace {
    pub fn new(capacity: usize) -> Self {
        Self {
            entries: VecDeque::with_capacity(capacity),
            capacity,
        }
    }

    pub fn push(&mut self, fact: MemoFact) {
        if self.entries.len() >= self.capacity {
            self.entries.pop_front();
        }
        self.entries.push_back(fact);
    }

    pub fn search(&self, keyword: &str) -> Vec<MemoFact> {
        let kw = keyword.to_lowercase().replace(['-', '_'], " ");
        self.entries
            .iter()
            .filter(|f| {
                f.key.to_lowercase().replace(['-', '_'], " ").contains(&kw)
                    || f.value
                        .to_lowercase()
                        .replace(['-', '_'], " ")
                        .contains(&kw)
            })
            .cloned()
            .collect()
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for ImmediateTrace {
    fn default() -> Self {
        Self::new(DEFAULT_CAPACITY)
    }
}
