use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginContext {
#[serde(default)]
pub local_state: HashMap<String, Value>,
#[serde(default)]
pub global_state: HashMap<String, Value>,
}
impl PluginContext {
pub fn new() -> Self {
Self {
local_state: HashMap::new(),
global_state: HashMap::new(),
}
}
pub fn with_global_state(global_state: HashMap<String, Value>) -> Self {
Self {
local_state: HashMap::new(),
global_state,
}
}
pub fn get_local(&self, key: &str) -> Option<&Value> {
self.local_state.get(key)
}
pub fn set_local(&mut self, key: impl Into<String>, value: Value) {
self.local_state.insert(key.into(), value);
}
pub fn get_global(&self, key: &str) -> Option<&Value> {
self.global_state.get(key)
}
pub fn set_global(&mut self, key: impl Into<String>, value: Value) {
self.global_state.insert(key.into(), value);
}
}
impl Default for PluginContext {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct PluginContextTable {
#[serde(default)]
pub global_state: HashMap<String, Value>,
#[serde(default)]
pub local_states: HashMap<Uuid, HashMap<String, Value>>,
}
impl PluginContextTable {
pub fn new() -> Self {
Self::default()
}
pub fn take_context(&mut self, plugin_id: Uuid) -> PluginContext {
PluginContext {
local_state: self.local_states.remove(&plugin_id).unwrap_or_default(),
global_state: self.global_state.clone(),
}
}
pub fn snapshot_context(&self, plugin_id: Uuid) -> PluginContext {
PluginContext {
local_state: self
.local_states
.get(&plugin_id)
.cloned()
.unwrap_or_default(),
global_state: self.global_state.clone(),
}
}
pub fn store_context(&mut self, plugin_id: Uuid, ctx: PluginContext) {
self.global_state = ctx.global_state;
self.local_states.insert(plugin_id, ctx.local_state);
}
pub fn len(&self) -> usize {
self.local_states.len()
}
pub fn is_empty(&self) -> bool {
self.local_states.is_empty()
}
}