use std::collections::HashMap;
use gen_utils::error::Error;
use crate::value::{Function, Value};
use super::{Else, Parent, PropKey};
#[derive(Debug, Clone, Default)]
pub struct Polls {
pub binds: Option<Binds>,
pub events: Option<Events>,
}
impl Polls {
pub fn bind_mut(&mut self) -> &mut Binds {
self.binds.get_or_insert_with(Default::default)
}
pub fn event_mut(&mut self) -> &mut Events {
self.events.get_or_insert_with(Default::default)
}
pub fn insert_prop(&mut self, key: &str, value: PropComponent) -> () {
self.bind_mut()
.entry(key.to_string())
.or_insert_with(Default::default)
.push(value);
}
pub fn insert_event(&mut self, value: EventComponent) -> () {
self.event_mut().push(value);
}
}
pub type Binds = HashMap<String, Vec<PropComponent>>;
pub type Events = Vec<EventComponent>;
#[derive(Debug, Clone)]
pub struct PropComponent {
pub id: String,
pub name: String,
pub prop: Prop,
pub as_prop: Option<String>,
pub father_ref: Option<Parent>,
}
#[derive(Debug, Clone)]
pub enum Prop {
Value(PropKV),
Else(Vec<PropKV>),
}
impl Prop {
pub fn as_str(&self) -> &str {
match self {
Prop::Value(kv) => kv.key.as_str(),
Prop::Else(_) => Else::SUGAR_SIGN,
}
}
}
impl ToString for Prop {
fn to_string(&self) -> String {
self.as_str().to_string()
}
}
#[derive(Debug, Clone)]
pub struct PropKV {
pub key: String,
pub value: Value,
}
impl PropKV {
pub fn new(key: String, value: Value) -> Self {
PropKV { key, value }
}
}
#[derive(Debug, Clone)]
pub struct EventComponent {
pub id: String,
pub name: String,
pub callbacks: HashMap<String, CallbackFn>,
}
impl EventComponent {
pub fn convert_callbacks(
callbacks: &HashMap<PropKey, Value>,
) -> Result<HashMap<String, CallbackFn>, Error> {
let mut res = HashMap::new();
for (key, value) in callbacks {
let func = value.as_fn()?;
res.insert(
func.name.to_string(),
CallbackFn::new(func, key.name.to_string()),
);
}
Ok(res)
}
}
#[derive(Debug, Clone)]
pub struct CallbackFn {
pub func: Function,
pub event: String,
}
impl CallbackFn {
pub fn new(func: Function, event: String) -> Self {
CallbackFn { func, event }
}
}