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
//! redmaple is the central data-structure that is underlying the whole crate

use std::{cmp, fmt::Debug};

use self::{event_group::EventKind, id::ID};

/// event module holds the types and functions that events could take and the operations that they
/// can do.
pub mod event_group;

/// id module holds the implementation of ID type
pub mod id;

/// versioned keeps the version of an stateful item
/// `RedMaple` is essentially a series of related events that form a state
///
/// * `id`: of type ID
/// * `events`: a list of entities that happened in time series
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RedMaple<T>
where
    T: EventKind + Sized + Clone + PartialEq + Eq + PartialOrd + Ord,
{
    events: Vec<T>,
}

impl<T> RedMaple<T>
where
    T: EventKind + Sized + Clone + PartialEq + Eq + PartialOrd + Ord,
{
    /// Creates a new instance of [`RedMaple`]
    ///
    /// * `view_mode`: sets the view mode of the `RedMaple`
    #[must_use]
    pub const fn new(events: Vec<T>) -> Self {
        Self { events }
    }

    // /// Gets the ID of the `RedMaple`
    // #[must_use]
    // pub const fn id(&self) -> &ValidRedMapleID {
    //     &self.id
    // }

    /// Gets an array of the events of the `RedMaple`
    #[must_use]
    pub const fn events(&self) -> &Vec<T> {
        &self.events
    }

    /// appends an event to the redmaple, while at the same time consuming it
    #[must_use]
    pub fn into_appended(self, event: T) -> Self {
        let mut s = self;
        s.events.push(event);
        s.events.sort();
        s
    }

    /// checks for the time created
    #[must_use]
    pub fn time_created(&self) -> Option<&time::OffsetDateTime> {
        self.events.first().map(EventKind::time)
    }

    /// checks for the updated time
    #[must_use]
    pub fn time_updated(&self) -> Option<&time::OffsetDateTime> {
        self.events.last().map(EventKind::time)
    }
}

/// A thin wrapper around [`ID`] that validates that the [`ID`] is coming from an [`Entry`]
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ValidRedMapleID(ID);

impl ValidRedMapleID {
    /// exposes the inner [`ID`] of the [`Entry`]
    #[must_use]
    pub const fn inner(&self) -> &ID {
        &self.0
    }
}

// /// Error type when a dealing with a subscriber
// #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
// pub enum SubscriberError {
//     /// when subscriber is in the list
//     #[error("Could not find the subscriber you are looking for: {0}")]
//     CouldNotFindSubscriber(ID),
// }

// /// [`SubscriberList`] is wrapper around  `Vec<ID>` which is there to ensure that the subscriber
// /// list follows some gurantees, like not having duplicates and being ordered.
// #[derive(Clone, Debug, PartialEq, Eq)]
// pub struct SubscriberList(Vec<ID>);
// impl SubscriberList {
//     /// Creates [`SubscriberLists`] but first sorts the given [`ID`] list and and then checks for
//     /// duplicated subscribers, if found removes duplicates.
//     ///
//     /// # Parameters
//     ///
//     /// ## `D` or `deduplicator`
//     /// this function will be used inside a fold function after the list was sorted.
//     /// so for a case of a sorted list you can just use:
//     ///
//     ///```
//     /// use redmaple::id::ID;
//     /// |mut list:Vec<ID> , item: &ID| {
//     ///   if list.last() != Some(item) {
//     ///     list.push(item.to_owned());
//     ///   };
//     ///   list
//     /// };
//     ///```
//     /// note however that `list.last()` is the only item it will check. So if the list is not
//     /// sorted it will fail to detect duplicates.
//     /// In case you don't want a sorted list you can instead use this:
//     ///
//     ///```
//     /// use  redmaple::id::ID;
//     /// let a = |mut list: Vec<ID>, item: &ID| {
//     ///   if !list.contains(item)  {
//     ///     list.push(item.to_owned());
//     ///   };
//     ///   list
//     /// };
//     ///
//     ///```
//     /// this is less performant because all of the new list will be checked before a new item is
//     /// added. While for the sorted list you only need to check if the last item is equal to the
//     /// current one.
//     ///
//     /// you might also not want to deduplicate in which case you should just add items to the list,
//     /// regardless:
//     ///
//     ///```
//     /// use redmaple::id::ID;
//     /// |mut list: Vec<ID>, item: &ID| {
//     ///   list.push(item.to_owned());
//     ///   list
//     /// };
//     ///```
//     ///
//     ///
//     /// ## `S` or `sorter`
//     ///
//     /// This function will be used to sort the list before it gets deduplicated.
//     ///
//     /// An example would be:
//     ///
//     /// ```
//     /// use redmaple::id::ID;
//     /// |a: &ID , b: &ID| {
//     ///   Ord::cmp(a, b)
//     /// };
//     /// ```
//     ///
//     #[must_use]
//     pub fn new<S, D>(members: &[ID], sorter: S, deduplicator: D) -> Self
//     where
//         S: FnMut(&&ID, &&ID) -> Ordering,
//         D: FnMut(Vec<ID>, &ID) -> Vec<ID>,
//     {
//         Self(members.iter().sorted_by(sorter).fold(vec![], deduplicator))
//     }

//     /// a very simple sorted which compares the first ID with the second ID
//     #[allow(clippy::trivially_copy_pass_by_ref)]
//     #[must_use]
//     pub fn simple_sorter(a: &&ID, b: &&ID) -> Ordering {
//         Ord::cmp(a, b)
//     }

//     /// a very simple deduplicator that sees if the last id in the list is the same as the one
//     /// that is given, if so, it will add the item to the list and return the list.
//     ///
//     /// You should note that this function does not "seem" to be purely functional as it takes a
//     /// mutable list. However, you should consider that the variable is now owned by the function.
//     /// as such it is not a shared mutable reference between different functions.
//     /// This will not comprimise the state of the application, While at the sametime improves
//     /// performance considerably by not cloning every single element time and times again.
//     ///
//     /// another approach could be to copy around the list on each item. which is more "pure". but
//     /// misses the point of "pureness" for a worse performance.
//     #[must_use]
//     pub fn simple_deduplicator(mut list: Vec<ID>, item: &ID) -> Vec<ID> {
//         if list.last() != Some(item) {
//             list.push(item.clone());
//         }
//         list
//     }

//     /// Creates a reference to see the inner vector.
//     #[must_use]
//     pub const fn inner(&self) -> &Vec<ID> {
//         &self.0
//     }

//     /// Returns the inner vector and consumes itself in the process.
//     #[must_use]
//     #[allow(clippy::missing_const_for_fn)] // currently a destructor method cannot be const
//     pub fn into_inner(self) -> Vec<ID> {
//         self.0
//     }
// }
// #[cfg(test)]
// mod tests {
//     use uuid::Uuid;

//     use super::*;

//     #[test]
//     fn make_empty_subscribers_list() {
//         let empty_list: Vec<ID> = vec![];
//         let empty_subscribers_list = SubscriberList::new(
//             &empty_list,
//             SubscriberList::simple_sorter,
//             SubscriberList::simple_deduplicator,
//         );

//         assert_eq!(empty_subscribers_list.into_inner(), vec![]);
//     }

//     #[test]
//     fn make_a_sorted_list() {
//         let (item1, item2, item3, item4) = (
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//         );
//         let mut sorted_list = vec![item1.clone(), item2.clone(), item3.clone(), item4.clone()];
//         sorted_list.sort();

//         let full_list: Vec<ID> = vec![item1, item2, item3, item4];
//         let new_subscribers_list = SubscriberList::new(
//             &full_list,
//             SubscriberList::simple_sorter,
//             SubscriberList::simple_deduplicator,
//         );
//         assert_eq!(new_subscribers_list.into_inner(), sorted_list);
//     }

//     #[test]
//     fn make_a_sorted_deduplicated_list() {
//         let (item1, item2, item3, item4) = (
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//             ID::new(Uuid::new_v4()),
//         );
//         let mut sorted_list = vec![
//             item1.clone(),
//             item2.clone(),
//             item3.clone(),
//             item4.clone(),
//             item2.clone(),
//         ];
//         sorted_list.sort();
//         sorted_list.dedup();

//         let full_list: Vec<ID> = vec![item1, item2, item3, item4];
//         let new_subscribers_list = SubscriberList::new(
//             &full_list,
//             SubscriberList::simple_sorter,
//             SubscriberList::simple_deduplicator,
//         );
//         assert_eq!(new_subscribers_list.into_inner(), sorted_list);
//     }
// }

impl<T> PartialOrd for RedMaple<T>
where
    T: EventKind + Sized + Clone + PartialEq + Eq + PartialOrd + Ord,
{
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.time_created().cmp(&other.time_created()))
    }
}

impl<T> Ord for RedMaple<T>
where
    T: EventKind + Sized + Clone + PartialEq + Eq + PartialOrd + Ord,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.time_created().cmp(&other.time_created())
    }
}