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
mod row;

pub use row::CollectionRow;

use std::{
    ops::{Deref, DerefMut},
    path::PathBuf,
};

use versatile_data::{Data, DataOption, Operation};

use crate::Database;

pub struct Collection {
    pub(crate) data: Data,
    id: i32,
    name: String,
}
impl Collection {
    pub fn new(data: Data, id: i32, name: impl Into<String>) -> Self {
        Self {
            data,
            id,
            name: name.into(),
        }
    }
    pub fn id(&self) -> i32 {
        self.id
    }
    pub fn name(&self) -> &str {
        &self.name
    }
}
impl Deref for Collection {
    type Target = Data;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}
impl DerefMut for Collection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl Database {
    pub fn collections(&self) -> Vec<String> {
        self.collections
            .iter()
            .map(|(_, x)| x.name().to_owned())
            .collect()
    }

    pub fn collection(&self, id: i32) -> Option<&Collection> {
        self.collections.get(&id)
    }
    pub fn collection_mut(&mut self, id: i32) -> Option<&mut Collection> {
        self.collections.get_mut(&id)
    }
    pub fn collection_id(&self, name: &str) -> Option<i32> {
        self.collections_map
            .contains_key(name)
            .then(|| *self.collections_map.get(name).unwrap())
    }
    pub fn collection_id_or_create(&mut self, name: &str) -> i32 {
        if self.collections_map.contains_key(name) {
            *self.collections_map.get(name).unwrap()
        } else {
            self.collection_by_name_or_create(name)
        }
    }

    pub fn delete_collection(&mut self, name: &str) {
        let collection_id = self.collections_map.get(name).map_or(0, |x| *x);
        if collection_id > 0 {
            if let Some(collection) = self.collections.get(&collection_id) {
                collection.data.all().iter().for_each(|row| {
                    self.delete_recursive(&CollectionRow::new(collection_id, *row));
                    if let Some(collection) = self.collection_mut(collection_id) {
                        collection.update(&Operation::Delete { row: *row });
                    }
                });
            }
            self.collections_map.remove(name);
            self.collections.remove(&collection_id);

            let mut dir = self.collections_dir.clone();
            dir.push(collection_id.to_string() + "_" + name);
            std::fs::remove_dir_all(&dir).unwrap();
        }
    }

    pub(super) fn create_collection(&mut self, id: i32, name: &str, dir: PathBuf) {
        let collection = Collection::new(
            Data::new(
                dir,
                self.collection_settings
                    .get(name)
                    .map_or(DataOption::default(), |f| f.clone()),
            ),
            id,
            name,
        );
        self.collections_map.insert(name.to_string(), id);
        self.collections.insert(id, collection);
    }
    fn collection_by_name_or_create(&mut self, name: &str) -> i32 {
        let mut max_id = 0;
        if self.collections_dir.exists() {
            for d in self.collections_dir.read_dir().unwrap() {
                let d = d.unwrap();
                if d.file_type().unwrap().is_dir() {
                    if let Some(fname) = d.file_name().to_str() {
                        let s: Vec<&str> = fname.split("_").collect();
                        if s.len() > 1 {
                            if let Ok(i) = s[0].parse() {
                                max_id = std::cmp::max(max_id, i);
                            }
                            if s[1] == name {
                                self.create_collection(max_id, name, d.path());
                                return max_id;
                            }
                        }
                    }
                }
            }
        }
        let collection_id = max_id + 1;
        self.create_collection(collection_id, name, {
            let mut collecion_dir = self.collections_dir.clone();
            collecion_dir.push(&(collection_id.to_string() + "_" + name));
            collecion_dir
        });
        collection_id
    }
}