use jam_types::{Hash, ServiceId};
use parking_lot::Mutex;
use schnellru::{ByLength, LruMap};

/// This cache stores service IDs and [`ExecEnvRef`](corevm_host::StorageKey::ExecEnvRef) hashes
/// of guests that timed out.
pub struct ExecCache {
	cache: Mutex<LruMap<ServiceId, Hash>>,
}

impl ExecCache {
	pub fn new(max_guests: u32) -> Self {
		Self { cache: Mutex::new(LruMap::new(ByLength::new(max_guests))) }
	}

	#[must_use]
	pub fn is_timed_out(&self, id: ServiceId) -> bool {
		self.cache.lock().get(&id).is_some()
	}

	/// Returns [`ExecEnvRef`](corevm_host::StorageKey::ExecEnvRef) hash that timed out.
	pub fn get_timed_out(&self, id: ServiceId) -> Option<Hash> {
		self.cache.lock().get(&id).copied()
	}

	pub fn set_timed_out(&self, id: ServiceId, exec_env_ref_hash: Hash) {
		self.cache.lock().insert(id, exec_env_ref_hash);
	}

	pub fn remove(&self, id: ServiceId) {
		self.cache.lock().remove(&id);
	}
}
