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
use std::num::NonZeroU32;

use futures::FutureExt;
use hashbrown::HashMap;
use uuid::Uuid;

use crate::Data;

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Activity {
    Inactive = 0,
    Active = 1,
}
impl Default for Activity {
    fn default() -> Self {
        Self::Active
    }
}

#[derive(Debug, Clone)]
pub enum Term {
    Default,
    Overwrite(u64),
}
impl Default for Term {
    fn default() -> Self {
        Self::Default
    }
}

#[derive(Default, Debug)]
pub struct Record {
    pub activity: Activity,
    pub term_begin: Term,
    pub term_end: Term,
    pub fields: HashMap<String, Vec<u8>>,
}

pub enum Operation {
    New(Record),
    Update { row: NonZeroU32, record: Record },
    Delete { row: NonZeroU32 },
}

pub fn create_uuid() -> u128 {
    Uuid::new_v4().as_u128()
}

impl Data {
    /// Perform operations to register, update, and delete data.
    pub async fn update(&mut self, operation: Operation) -> Option<NonZeroU32> {
        match operation {
            Operation::New(record) => {
                let row = self.serial.next_row().await;
                self.update_field(row, record, true).await;
                Some(row)
            }
            Operation::Update { row, record } => {
                self.update_field(row, record, false).await;
                Some(row)
            }
            Operation::Delete { row } => {
                self.delete(row).await;
                None
            }
        }
    }

    async fn delete(&mut self, row: NonZeroU32) {
        self.load_fields();

        futures::future::join(
            futures::future::join(async { self.serial.delete(row) }, async {
                futures::future::join_all(self.fields_cache.iter_mut().map(|(_, v)| async {
                    v.delete(row);
                }))
                .await
            }),
            async {
                let mut futs = vec![];
                if let Some(ref mut f) = self.uuid {
                    futs.push(
                        async {
                            f.delete(row);
                        }
                        .boxed_local(),
                    );
                }
                if let Some(ref mut f) = self.activity {
                    futs.push(
                        async {
                            f.delete(row);
                        }
                        .boxed_local(),
                    );
                }
                if let Some(ref mut f) = self.term_begin {
                    futs.push(
                        async {
                            f.delete(row);
                        }
                        .boxed_local(),
                    );
                }
                if let Some(ref mut f) = self.term_end {
                    futs.push(
                        async {
                            f.delete(row);
                        }
                        .boxed_local(),
                    );
                }
                if let Some(ref mut f) = self.last_updated {
                    futs.push(
                        async {
                            f.delete(row);
                        }
                        .boxed_local(),
                    );
                }
                futures::future::join_all(futs).await;
            },
        )
        .await;
    }

    async fn update_field(&mut self, row: NonZeroU32, record: Record, with_uuid: bool) {
        for (key, _) in &record.fields {
            if !self.fields_cache.contains_key(key) {
                self.create_field(key);
            }
        }

        futures::future::join_all([
            async {
                futures::future::join_all(self.fields_cache.iter_mut().filter_map(
                    |(key, field)| {
                        if let Some(v) = record.fields.get(key) {
                            Some(field.update(row, v))
                        } else {
                            None
                        }
                    },
                ))
                .await;
            }
            .boxed_local(),
            async {
                if with_uuid {
                    if let Some(ref mut uuid) = self.uuid {
                        uuid.update_with_allocate(row, Uuid::new_v4().as_u128())
                            .await;
                    }
                }
            }
            .boxed_local(),
            async {
                if let Some(ref mut f) = self.last_updated {
                    f.update_with_allocate(row, Self::now()).await;
                }
            }
            .boxed_local(),
            async {
                if let Some(ref mut f) = self.activity {
                    f.update_with_allocate(row, record.activity as u8).await;
                }
            }
            .boxed_local(),
            async {
                if let Some(ref mut f) = self.term_begin {
                    f.update_with_allocate(
                        row,
                        if let Term::Overwrite(term) = record.term_begin {
                            term
                        } else {
                            Self::now()
                        },
                    )
                    .await;
                }
            }
            .boxed_local(),
            async {
                if let Some(ref mut f) = self.term_end {
                    f.update_with_allocate(
                        row,
                        if let Term::Overwrite(term) = record.term_end {
                            term
                        } else {
                            0
                        },
                    )
                    .await;
                }
            }
            .boxed_local(),
        ])
        .await;
    }
}