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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//  ------------------------------------------------------------------
//  Airone
//  is a Rust library which provides a simple in-memory,
//  write-on-update database that is persisted
//  to an append-only transaction file.
//
//  Copyright © 2022 Massimo Gismondi
//
//  This file is part of Airone.
//  Airone is free software: you can redistribute it and/or
//  modify it under the terms of the GNU Affero General Public License
//  as published by the Free Software Foundation, either version 3
//  of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU Affero General Public License
//  along with this program. If not, see <https://www.gnu.org/licenses/>.
//  ------------------------------------------------------------------

use crate::AironeError;
use crate::Operation;
use crate::SingleChange;

use std::io::{BufRead, BufWriter, Read, Write};

/// A value that can be converted to a String
/// properly escaping characters that are not
/// allowed in airone's CSV format
///
/// Sometimes it's enough to format!() the value,
/// sometimes it needs custom conversions.
pub trait PersistableValue
{
    fn to_persistable_string(&self) -> String;
}

/// A value that can be converted from the String
/// to its actual type.
///
/// Sometimes it's enough to parse the value,
/// sometimes it needs custom conversions.
pub trait LoadableValue
{
    fn from_persistable_string(s: &str) -> Self;
}

macro_rules! impl_persistable_value_with_format {
    ($($t:ty),*) => {
        $(
            impl PersistableValue for $t
            {

                fn to_persistable_string(&self) -> String
                {
                    format!("{}", &self)
                }
            }
        )*
    };
}
impl_persistable_value_with_format!(
    bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

macro_rules! impl_loadable_value_with_parse {
    ($($t:ty),*) => {
        $(
            impl LoadableValue for $t
            {
                fn from_persistable_string(s: &str) -> $t
                {
                    return (s.parse::<$t>().unwrap()).clone()
                }
            }
        )*
    };
}
impl_loadable_value_with_parse!(
    bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

impl PersistableValue for String
{
    fn to_persistable_string(&self) -> String
    {
        let a = &self.clone();
        return a
            .replace("\n", "\\n")
            .replace("\r", "\\r")
            .replace("\t", "\\t")
            .replace("\"", "\\\"");
    }
}
impl LoadableValue for String
{
    fn from_persistable_string(s: &str) -> String
    {
        let a = s.clone();
        return a
            .replace("\\n", "\n")
            .replace("\\r", "\r")
            .replace("\\t", "\t")
            .replace("\\\"", "\"");
    }
}

impl<T> PersistableValue for Option<T>
where
    T: PersistableValue
{
    fn to_persistable_string(&self) -> String
    {
        if let Some(el) = &self
        {
            return el.to_persistable_string();
        }
        else
        {
            return String::new();
        }
    }
}

impl<A: LoadableValue> LoadableValue for Option<A>
{
    fn from_persistable_string(s: &str) -> Option<A>
    {
        if s.len() > 0
        {
            let b: A = LoadableValue::from_persistable_string(s);
            return Some(b);
        }
        else
        {
            return None;
        }
    }
}

/// Represents a struct that can be
/// serialized as a single line.
///
/// Each field type of the struct must implement
/// [PersistableValue]
pub trait CsvSerializable
{
    fn serialize_object(&self) -> String;
}

/// Represents a struct that can be
/// deserialized from a single line.
///
/// Each field type of the struct must implement
/// [LoadableValue]
pub trait CsvLoadable
{
    fn load_object(s: &String) -> Self;
}

pub trait GetSetObject
{
    fn set_str(&mut self, key: &str, value: &str);
}

/// This trait exposes public methods to access the data
pub trait Database<T>: InternalDatabaseMethods<T>
where
    T: CsvLoadable + CsvSerializable + GetSetObject
{
    /// Constructor method, initializing the save file
    /// named as the struct you passed to the [airone_db!] macro
    fn new() -> Self;

    /// Constructor method, initializing the save file
    /// using the given name.
    ///
    /// Do _NOT_ include the file extension.
    fn new_with_filename(custom_filename: &str) -> Self;

    /// Returns a reference to the element at the provided index
    fn get(&self, index: usize) -> Result<&T, AironeError>
    {
        match self.get_elements().get(index)
        {
            Some(e) => Ok(e),
            None => Err(AironeError::OutOfBound)
        }
    }

    /// Returns a non-mutable reference to the inner list.
    ///
    /// You are forced to change data through the provided methods
    /// of Airone, so that changes are correctly persisted.
    fn get_all(&self) -> &Vec<T>
    {
        return self.get_elements();
    }

    /// Adds a new element to the list at the given index position
    fn insert(&mut self, index: usize, element: T) -> Result<(), AironeError>
    {
        self.transact_insert_change(self.internal_op_add(&element, index))?;
        self.get_elements_mut().insert(index, element);
        Ok(())
    }

    /// Adds a new element to the end of the list
    fn push(&mut self, element: T) -> Result<(), AironeError>
    {
        return self.insert(self.get_elements().len(), element);
    }

    /// Adds multiple elements to the end of the list, automatically reducing the number of syscalls to write them to disk
    fn bulk_push(&mut self, elements: Vec<T>) -> Result<(), AironeError>
    {
        let current_autocommit_state = self.get_auto_commit();

        self.set_auto_commit(false);
        for el in elements
        {
            self.push(el)?;
        }
        self.set_auto_commit(current_autocommit_state);
        if self.get_auto_commit()
        {
            self.commit()?;
        }
        return Ok(());
    }

    /// Removes the first element of the list
    fn pop(&mut self) -> Result<(), AironeError>
    {
        if let Some(el) = self.get_elements_mut().pop()
        {
            self.transact_insert_change(self.internal_op_delete(self.get_elements().len(), &el))?;
            Ok(())
        }
        else
        {
            return Err(AironeError::ListAlreadyEmpty);
        }
    }

    /// Removes the element at the specified index from the list
    fn remove(&mut self, index: usize) -> Result<(), AironeError>
    {
        if self.get_elements().len() == 0
        {
            self.rollback()?;
            return Err(AironeError::ListAlreadyEmpty);
        }
        if index < self.get_elements().len()
        {
            let el = self.get_elements_mut().remove(index);
            self.transact_insert_change(self.internal_op_delete(index, &el))?;
            return Ok(());
        }
        else
        {
            self.rollback()?;
            return Err(AironeError::OutOfBound);
        }
    }

    /// Removes the elements at the specified indices from the list,
    /// automatically reducing the number of syscalls to write them to disk
    fn bulk_remove(&mut self, indices: Vec<usize>) -> Result<(), AironeError>
    {
        for index in indices.iter()
        {
            if index >= &self.get_elements().len()
            {
                self.rollback()?;
                return Err(AironeError::OutOfBound);
            }
        }
        if indices.len() > self.get_elements().len()
        {
            self.rollback()?;
            return Err(AironeError::OutOfBound);
        }

        let current_autocommit_state = self.get_auto_commit();
        self.set_auto_commit(false);

        let mut my_indices = indices.clone();
        my_indices.sort();
        my_indices.reverse();
        for index in my_indices.iter()
        {
            self.remove(index.clone())?;
        }

        self.set_auto_commit(current_autocommit_state);
        if self.get_auto_commit()
        {
            self.commit()?;
        }
        Ok(())
    }

    /// Returns the current number of elements in the list
    fn len(&self) -> usize
    {
        self.get_elements().len()
    }

    /// Filters the elements with the given predicate.
    /// Returns a list of indices that match the filter.
    ///
    /// You can later use those indices with [bulk_remove](Database::bulk_remove) methods or `bulk_set_$field_name` setters generated by the macro.
    fn filter<F>(&self, f: F) -> Vec<usize>
    where
        F: Fn(&T) -> bool
    {
        return self
            .get_elements()
            .iter()
            .enumerate()
            .filter(|(_k, v)| f(v))
            .map(|(k, _v)| k)
            .collect();
    }

    // Transazioni
    /// Commits a transaction by saving change to disk
    fn commit(&mut self) -> Result<(), AironeError>
    {
        let list_changes = self.transact_get_list().clone();
        let writer = self.get_buf_writer();
        for el in list_changes
        {
            if writeln!(writer, "{}", el.apply_change.to_line()).is_err()
            {
                return Err(crate::AironeError::IOError);
            }
        }

        if self.get_buf_writer().flush().is_err()
        {
            return Err(crate::AironeError::IOError);
        }

        *self.transact_get_list_mut() = Vec::new();
        Ok(())
    }

    /// Rolls back data in memory to the last successfull commit.
    fn rollback(&mut self) -> Result<(), AironeError>
    {
        self.transact_get_list_mut().reverse();
        let list_changes = self.transact_get_list().clone();
        for el in list_changes
        {
            Self::apply_single_edit(self.get_elements_mut(), &el.revert_change)?;
        }

        *self.transact_get_list_mut() = Vec::new();
        Ok(())
    }

    /// Enables or disables autocommit
    ///
    /// Autocommit means that each change is instantly flushed to disk without having to call `commit()`. The rollback() function is useless in this state.
    ///
    /// Disabled autocommit means the you have to manually commit or rollback changes.
    fn set_auto_commit(&mut self, new_state: bool);

    /// Returns the current auto-commit configuration
    fn get_auto_commit(&self) -> bool;
}

/// Internal methods shared by all db instances
pub trait InternalDatabaseMethods<T>
where
    T: CsvLoadable + CsvSerializable + GetSetObject
{
    //------------------------------------------
    // Internal operations
    //------------------------------------------
    fn internal_op_add(&self, new_object: &T, index_for_revert: usize) -> crate::SingleChange
    {
        return crate::SingleChange {
            apply_change: crate::Operation::Add {
                index: index_for_revert,
                serialized_object: T::serialize_object(new_object)
            },
            revert_change: crate::Operation::Delete {
                index: index_for_revert
            }
        };
    }
    fn internal_op_delete(&self, index: usize, removed_object: &T) -> crate::SingleChange
    {
        return crate::SingleChange {
            apply_change: crate::Operation::Delete { index: index },
            revert_change: crate::Operation::Add {
                index: index,
                serialized_object: removed_object.serialize_object()
            }
        };
    }
    fn internal_op_edit<C: PersistableValue>(
        &self,
        index: usize,
        key: &str,
        old_value: &C,
        new_value: &C
    ) -> crate::SingleChange
    {
        return crate::SingleChange {
            apply_change: crate::Operation::Edit {
                index,
                field_name: key.to_string(),
                new_value_str: new_value.to_persistable_string()
            },
            revert_change: crate::Operation::Edit {
                index,
                field_name: key.to_string(),
                new_value_str: old_value.to_persistable_string()
            }
        };
    }

    //
    fn get_elements(&self) -> &Vec<T>;
    fn get_elements_mut(&mut self) -> &mut Vec<T>;
    fn get_buf_writer(&mut self) -> &mut std::io::BufWriter<std::fs::File>;
    fn apply_single_edit(elements: &mut Vec<T>, operation: &Operation) -> Result<(), AironeError>
    {
        match operation
        {
            Operation::Add {
                index,
                serialized_object
            } =>
            {
                let el: T = T::load_object(&serialized_object);
                elements.insert(*index, el);
            }
            Operation::Delete { index } =>
            {
                elements.remove(*index);
            }
            Operation::Edit {
                index,
                field_name,
                new_value_str
            } =>
            {
                if let Some(el) = elements.get_mut(*index)
                {
                    el.set_str(field_name, new_value_str);
                }
                else
                {
                    return Err(crate::AironeError::OutOfBound);
                }
            }
        }

        Ok(())
    }
    fn transact_insert_change(&mut self, change: crate::SingleChange) -> Result<(), AironeError>;
    fn transact_get_list(&mut self) -> &Vec<SingleChange>;
    fn transact_get_list_mut(&mut self) -> &mut Vec<SingleChange>;

    /// Dumps the whole dataset to the given file writer
    fn full_dump<W>(objects: &Vec<T>, mut writer: BufWriter<W>)
    where
        W: Write
    {
        for element in objects
        {
            let string = element.serialize_object();
            writeln!(writer, "{}", string).unwrap();
        }
        writer.flush().unwrap();
    }

    /// Loads the whole dataset from a compacted file
    fn full_load(elements: &mut Vec<T>, filename: &str) -> Result<(), AironeError>
    {
        Self::load_base_data(elements, filename)?;
        Self::apply_edits(elements, filename)?;

        Ok(())
    }

    // ------------------------------------------
    // Quando il database viene istanziato,
    // devo caricare il JSON base e poi
    // applicare le modifiche
    // ------------------------------------------
    /// Carica il JSON di base senza applicare le modifiche
    fn load_base_data(elements: &mut Vec<T>, filename: &str) -> Result<(), AironeError>
    {
        // Carico JSON di base
        if let Ok(file) = std::fs::OpenOptions::new()
            .read(true)
            .open(format!("{}{}", filename, ".csv"))
        {
            let buf = std::io::BufReader::new(file);
            for line in buf.lines()
            {
                elements.push(T::load_object(match &line
                {
                    Ok(e) => e,
                    Err(_) => return Err(AironeError::IOError)
                }));
            }
            Ok(())
        }
        else
        {
            match std::fs::File::create(format!("{}{}", filename, ".csv"))
            {
                Ok(_) => Ok(()),
                Err(_) => return Err(AironeError::IOError)
            }
        }
    }

    /// Apply modifications contained
    /// in the transaction log file
    fn apply_edits(elements: &mut Vec<T>, filename: &str) -> Result<(), AironeError>
    {
        {
            let file = match std::fs::OpenOptions::new()
                .read(true)
                .open(format!("{}{}", filename, ".changes.csv"))
            {
                Ok(e) => e,
                Err(_) =>
                {
                    return Ok(());
                }
            };
            let reader = std::io::BufReader::new(file);

            for line in reader.lines()
            {
                let my_line = line.unwrap();
                Self::apply_single_edit(elements, &crate::Operation::parse_line(&my_line)?)?;
            }
        }

        // Svuoto file modifiche
        std::fs::File::create(format!("{}{}", filename, ".changes.csv")).unwrap();

        Ok(())
    }

    /// Salva su file il JSON intero compattato
    /// ed elimina il file delle modifiche
    fn compact(elements: &Vec<T>, filename: &str) -> Result<(), AironeError>
    {
        let file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(format!("{}{}", filename, ".csv"))
            .unwrap();
        let mut writer = std::io::BufWriter::new(file);
        Self::full_dump(elements, writer);

        Ok(())
    }
}