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
use std::sync::mpsc::Sender;

pub use versatile_data::search::{Field, Number, Term};
use versatile_data::{
    Activity, Condition as VersatileDataCondition, RowSet, Search as VersatileDataSearch,
};

use crate::{Collection, Database, Depend, RelationIndex};

#[derive(Clone)]
pub enum Condition {
    Activity(Activity),
    Term(Term),
    Row(Number),
    Uuid(u128),
    LastUpdated(Number),
    Field(String, Field),
    Narrow(Vec<Condition>),
    Wide(Vec<Condition>),
    Depend(Depend),
}

pub struct Search {
    collection_id: i32,
    conditions: Vec<Condition>,
}
impl Search {
    pub fn new(collection: &Collection) -> Self {
        Self {
            collection_id: collection.id(),
            conditions: Vec::new(),
        }
    }
    pub fn search(mut self, condition: Condition) -> Self {
        self.conditions.push(condition);
        self
    }
    pub fn default(mut self) -> Self {
        self.conditions
            .push(Condition::Term(Term::In(chrono::Local::now().timestamp())));
        self.conditions.push(Condition::Activity(Activity::Active));
        self
    }
    pub fn depend(mut self, condition: Depend) -> Self {
        self.conditions.push(Condition::Depend(condition));
        self
    }
    pub fn field(self, field_name: impl Into<String>, condition: Field) -> Self {
        self.search(Condition::Field(field_name.into(), condition))
    }

    fn exec_cond(
        collection: &Collection,
        relation: &RelationIndex,
        condtion: &Condition,
        tx: Sender<RowSet>,
    ) {
        match condtion {
            Condition::Activity(c) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::Activity(*c),
                    tx,
                );
            }
            Condition::Term(c) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::Term(c.clone()),
                    tx,
                );
            }
            Condition::Row(c) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::Row(c.clone()),
                    tx,
                );
            }
            Condition::Uuid(c) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::Uuid(c.clone()),
                    tx,
                );
            }
            Condition::LastUpdated(c) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::LastUpdated(c.clone()),
                    tx,
                );
            }
            Condition::Field(key, condition) => {
                VersatileDataSearch::search_exec_cond(
                    &collection.data,
                    &VersatileDataCondition::Field(key.to_owned(), condition.clone()),
                    tx,
                );
            }
            Condition::Depend(depend) => {
                let rel = relation.pends(depend.key(), depend.collection_row());
                let collection_id = collection.id();
                std::thread::spawn(move || {
                    let mut tmp = RowSet::default();
                    for r in rel {
                        if r.collection_id() == collection_id {
                            tmp.insert(r.row());
                        }
                    }
                    let tx = tx.clone();
                    tx.send(tmp).unwrap();
                });
            }
            Condition::Narrow(conditions) => {
                let (tx_inner, rx) = std::sync::mpsc::channel();
                for c in conditions {
                    let tx_inner = tx_inner.clone();
                    Self::exec_cond(collection, relation, c, tx_inner);
                }
                drop(tx_inner);
                std::thread::spawn(move || {
                    let mut is_1st = true;
                    let mut tmp = RowSet::default();
                    for mut rs in rx {
                        if is_1st {
                            tmp = rs;
                            is_1st = false;
                        } else {
                            tmp = tmp.intersection(&mut rs).map(|&x| x).collect();
                        }
                    }
                    tx.send(tmp).unwrap();
                });
            }
            Condition::Wide(conditions) => {
                let (tx_inner, rx) = std::sync::mpsc::channel();
                for c in conditions {
                    let tx_inner = tx_inner.clone();
                    Self::exec_cond(collection, relation, c, tx_inner);
                }
                drop(tx_inner);
                std::thread::spawn(move || {
                    let mut tmp = RowSet::default();
                    for ref mut rs in rx {
                        tmp.append(rs);
                    }
                    tx.send(tmp).unwrap();
                });
            }
        }
    }
    pub(super) fn result(&self, database: &Database) -> RowSet {
        let mut rows = RowSet::default();
        if let Some(collection) = database.collection(self.collection_id) {
            if self.conditions.len() > 0 {
                let (tx, rx) = std::sync::mpsc::channel();
                for c in &self.conditions {
                    Self::exec_cond(collection, &database.relation, c, tx.clone());
                }
                drop(tx);
                let mut fst = true;
                for rs in rx {
                    if fst {
                        rows = rs;
                        fst = false;
                    } else {
                        rows = rows.intersection(&rs).map(|&x| x).collect()
                    }
                }
            } else {
                for row in collection.data.all() {
                    rows.insert(row);
                }
            }
        }
        rows
    }
}