1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use erased_serde::{Deserializer, Serialize, Serializer};
use serde::de::DeserializeOwned;
use std::any::{Any, TypeId};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use crate::core::ItemID;

///
/// Config entity type must satisfy this constraint
///
pub trait EntityTrait: Send + Sync + Any {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn to_json_value(&self) -> Result<serde_json::Value, serde_json::Error>;
    fn deserialize(
        &mut self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<(), erased_serde::Error>;
}

impl<T> EntityTrait for T
where
    T: Send + Sync + Any + Serialize + DeserializeOwned,
{
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self as &mut dyn Any
    }

    fn deserialize(
        &mut self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<(), erased_serde::Error> {
        *self = T::deserialize(de)?;
        Ok(())
    }

    fn to_json_value(&self) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::to_value(self as &dyn erased_serde::Serialize)
    }
}

///
///
/// Metadata for configuration entity. This can be used as template for multiple config entity
///  instances.
///
///
pub struct Metadata {
    /// Identifier for this config entity.
    pub name: &'static str,
    pub type_id: TypeId,

    pub v_default: Arc<dyn EntityTrait>,
    pub v_min: Option<Box<dyn EntityTrait>>,
    pub v_max: Option<Box<dyn EntityTrait>>,
    pub v_one_of: Vec<Box<dyn EntityTrait>>,

    pub props: MetadataProps,

    pub fn_default: Box<dyn Fn() -> Box<dyn EntityTrait> + Send + Sync>,
    pub fn_copy_to: fn(&dyn Any, &mut dyn Any),
    pub fn_serialize_to: fn(&dyn Any, &mut dyn Serializer) -> Result<(), erased_serde::Error>,
    pub fn_deserialize_from:
        fn(&mut dyn Any, &mut dyn Deserializer) -> Result<(), erased_serde::Error>,

    /// Returns None if validation failed. Some(false) when source value was corrected.
    ///  Some(true) when value was correct.
    pub fn_validate: fn(&Metadata, &mut dyn Any) -> Option<bool>,
}

pub struct MetadataValInit<T> {
    pub v_default: T,

    pub v_min: Option<T>,
    pub v_max: Option<T>,
    pub v_one_of: Vec<T>,

    // Should be generated through derive macro
    pub fn_validate: fn(&Metadata, &mut dyn Any) -> Option<bool>,
}

#[derive(Debug)]
pub struct MetadataProps {
    pub disable_export: bool,
    pub disable_import: bool,
    pub hidden: bool,

    pub schema: Option<crate::Schema>,

    /// Source variable name. Usually same as 'name' unless another name is specified for it.
    pub varname: &'static str,
    pub description: &'static str,
}

pub mod lookups {
    pub trait HasSchema {
        fn get_schema(&self) -> Option<crate::Schema>;
    }

    impl<T: schemars::JsonSchema> HasSchema for T {
        fn get_schema(&self) -> Option<crate::Schema> {
            Some(schemars::schema_for!(T))
        }
    }

    pub trait NoSchema {
        fn get_schema(&self) -> Option<crate::Schema> {
            None
        }
    }

    trait AnyType {}
    impl<T> AnyType for T {}

    impl<T: AnyType> NoSchema for &T {}
}

impl Metadata {
    pub fn create_for_base_type<T>(
        name: &'static str,
        init: MetadataValInit<T>,
        props: MetadataProps,
    ) -> Self
    where
        T: EntityTrait + Clone + serde::de::DeserializeOwned + serde::ser::Serialize,
    {
        let retrive_opt_minmax = |val| {
            if let Some(v) = val {
                Some(Box::new(v) as Box<dyn EntityTrait>)
            } else {
                None
            }
        };

        let v_min = retrive_opt_minmax(init.v_min);
        let v_max = retrive_opt_minmax(init.v_max);
        let v_one_of: Vec<_> = init
            .v_one_of
            .iter()
            .map(|v| Box::new(v.clone()) as Box<dyn EntityTrait>)
            .collect();

        Self {
            name,
            type_id: TypeId::of::<T>(),
            v_default: Arc::new(init.v_default.clone()),
            v_min,
            v_max,
            v_one_of,
            props,
            fn_default: Box::new(move || Box::new(init.v_default.clone())),
            fn_copy_to: |from, to| {
                let from: &T = from.downcast_ref().unwrap();
                let to: &mut T = to.downcast_mut().unwrap();

                *to = from.clone();
            },
            fn_serialize_to: |from, to| {
                let from: &T = from.downcast_ref().unwrap();
                from.erased_serialize(to)?;

                Ok(())
            },
            fn_deserialize_from: |to, from| {
                let to: &mut T = to.downcast_mut().unwrap();
                *to = erased_serde::deserialize(from)?;

                Ok(())
            },
            fn_validate: init.fn_validate,
        }
    }
}

///
/// Helper methods for proc macro generated code
///
pub mod gen_helper {
    use std::any::Any;

    use crate::entity::Metadata;

    pub fn validate_min_max<T: 'static + Clone + Ord>(meta: &Metadata, val: &mut dyn Any) -> bool {
        let to: &mut T = val.downcast_mut().unwrap();
        let mut was_in_range = true;

        if let Some(val) = &meta.v_min {
            let from: &T = val.as_any().downcast_ref().unwrap();
            if *to < *from {
                was_in_range = false;
                *to = from.clone();
            }
        }

        if let Some(val) = &meta.v_max {
            let from: &T = val.as_any().downcast_ref().unwrap();
            if *from < *to {
                was_in_range = false;
                *to = from.clone();
            }
        }

        was_in_range
    }

    pub fn verify_one_of<T: 'static + Eq>(meta: &Metadata, val: &dyn Any) -> bool {
        if meta.v_one_of.is_empty() {
            return true;
        }

        let to: &T = val.downcast_ref().unwrap();
        meta.v_one_of
            .iter()
            .map(|v| v.as_any().downcast_ref::<T>().unwrap())
            .any(|v| *v == *to)
    }
}

///
///
/// Events are two directional ...
///
/// 1. Remote commit entity / Local commit entity
///     - 'on update' user observer hooked
///     - 'any value update' observer hooked
///
/// 2. Local commit entity silent
///     - 'any value update' observer hooked
///
/// 3. Local set retrieves entity update
///
pub struct EntityData {
    /// Unique entity id for program run-time
    id: ItemID,

    meta: Arc<Metadata>,
    fence: AtomicUsize,
    value: Mutex<Arc<dyn EntityTrait>>,

    hook: Arc<dyn EntityEventHook>,
}

impl EntityData {
    pub(crate) fn new(meta: Arc<Metadata>, hook: Arc<dyn EntityEventHook>) -> Self {
        Self {
            id: ItemID::new_unique(),
            fence: AtomicUsize::new(0), // This forces initial
            value: Mutex::new(meta.v_default.clone()),
            meta,
            hook,
        }
    }

    pub fn get_id(&self) -> ItemID {
        self.id
    }

    pub fn get_meta(&self) -> &Arc<Metadata> {
        &self.meta
    }

    pub fn get_update_fence(&self) -> usize {
        self.fence.load(Ordering::Relaxed)
    }

    pub fn get_value(&self) -> (&Arc<Metadata>, Arc<dyn EntityTrait>) {
        (&self.meta, self.value.lock().unwrap().clone())
    }

    /// If `silent` option is disabled, increase config set and source argument's fence
    ///  by 1, to make self and other instances of config set which shares the same core
    ///  be aware of this change.
    pub fn __apply_value(&self, value: Arc<dyn EntityTrait>) {
        debug_assert!(self.meta.type_id == value.as_any().type_id());

        {
            let mut lock = self.value.lock().unwrap();
            *lock = value;

            self.fence.fetch_add(1, Ordering::Release);
        }
    }

    ///
    /// Update config entity's central value by parsing given deserializer.
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Deserialization successful, validation successful.
    /// * `Ok(false)` - Deserialization successful, validation unsuccessful, as value was modified
    ///                 to satisfy validator constraint
    /// * `Err(_)` - Deserialization or validation has failed.
    ///
    pub fn update_value_from<'a, T>(&self, de: T) -> Result<bool, crate::core::Error>
    where
        T: serde::Deserializer<'a>,
    {
        let meta = &self.meta;
        let mut erased = <dyn erased_serde::Deserializer>::erase(de);
        let mut built = (meta.fn_default)();

        match built.deserialize(&mut erased) {
            Ok(_) => {
                let clean = match (meta.fn_validate)(&*meta, built.as_any_mut()) {
                    Some(clean) => clean,
                    None => return Err(crate::core::Error::ValueValidationFailed),
                };

                let built: Arc<dyn EntityTrait> = built.into();
                self.__apply_value(built);

                Ok(clean)
            }
            Err(e) => {
                log::error!(
                    "(Deserialization Failed) {}(var:{}) \n\nERROR: {e:#?}",
                    meta.name,
                    meta.props.varname,
                );
                Err(e.into())
            }
        }
    }

    pub fn __notify_value_change(&self, make_storage_dirty: bool) {
        self.hook.on_value_changed(self, !make_storage_dirty);
    }
}

pub(crate) trait EntityEventHook: Send + Sync {
    fn on_value_changed(&self, data: &EntityData, silent: bool);
}