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
use std::sync::{
    Arc,
    RwLock
};
use std::thread;
use std::collections::HashMap;
use uuid::Uuid;

pub use idx_sized::{
    IdxSized
    ,RowSet
};

mod serial;
use serial::SerialNumber;

mod field;
pub use field::FieldData;

pub mod search;
pub use search::{
    Search
    ,Condition
    ,Order
};

mod operation;
pub use operation::*;

pub mod prelude;

pub struct Data{
    data_dir:String
    ,serial: Arc<RwLock<SerialNumber>>
    ,uuid: Arc<RwLock<IdxSized<u128>>>
    ,activity: Arc<RwLock<IdxSized<u8>>>
    ,term_begin: Arc<RwLock<IdxSized<i64>>>
    ,term_end: Arc<RwLock<IdxSized<i64>>>
    ,last_updated: Arc<RwLock<IdxSized<i64>>>
    ,fields_cache:HashMap<String,Arc<RwLock<FieldData>>>
}
impl Data{
    pub fn new(dir:&str)-> Result<Self,std::io::Error>{
        if !std::path::Path::new(dir).exists(){
            std::fs::create_dir_all(dir).unwrap();
        }
        Ok(Data{
            data_dir:dir.to_string()
            ,serial:Arc::new(RwLock::new(SerialNumber::new(&(dir.to_string()+"/serial"))?))
            ,uuid:Arc::new(RwLock::new(IdxSized::new(&(dir.to_string()+"/uuid.i"))?))
            ,activity:Arc::new(RwLock::new(IdxSized::new(&(dir.to_string()+"/activity.i"))?))
            ,term_begin:Arc::new(RwLock::new(IdxSized::new(&(dir.to_string()+"/term_begin.i"))?))
            ,term_end:Arc::new(RwLock::new(IdxSized::new(&(dir.to_string()+"/term_end.i"))?))
            ,last_updated:Arc::new(RwLock::new(IdxSized::new(&(dir.to_string()+"/last_updated.i"))?))
            ,fields_cache:HashMap::new()
        })
    }

    pub fn update(
        &mut self
        ,operation:&Operation
    )->u32{
        match operation{
            Operation::New{
                activity
                ,term_begin
                ,term_end
                ,fields
            }=>{
                self.create_row(activity,term_begin,term_end,fields)
            }
            ,Operation::Update{
                row
                ,activity
                ,term_begin
                ,term_end
                ,fields
            }=>{
                self.update_row(*row,activity,term_begin,term_end,fields);
                *row
            }
            ,Operation::Delete{row}=>{
                self.delete(*row);
                0
            }
        }
    }

    pub fn create_row(
        &mut self
        ,activity:&Activity
        ,term_begin:&Term
        ,term_end:&Term
        ,fields:&Vec<KeyValue>
    )->u32{
        if self.serial.read().unwrap().exists_blank(){
            let row=self.serial.write().unwrap().pop_blank().unwrap();
            self.create_row_recycled(row,activity,term_begin,term_end,fields);
            row
        }else{
            let row=self.serial.write().unwrap().add().unwrap();
            self.create_row_new(row,activity,term_begin,term_end,fields);
            row
        }
    }
    fn create_row_recycled(&mut self,row:u32,activity:&Activity,term_begin:&Term,term_end:&Term,fields:&Vec<KeyValue>){
        let mut handles=Vec::new();

        let index=self.uuid.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().update(row,Uuid::new_v4().as_u128()); //recycled serial_number,uuid recreate.
        }));

        handles.push(self.update_activity_async(row,*activity));
    
        handles.push(self.update_term_begin_async(row,if let Term::Overwrite(term_begin)=term_begin{
            *term_begin
        }else{
            chrono::Local::now().timestamp()
        }));

        handles.push(self.update_term_end_async(row,if let Term::Overwrite(term_end)=term_end{
            *term_end
        }else{
            0
        }));

        handles.append(&mut self.update_fields(row,fields));

        for h in handles{
            h.join().unwrap();
        }
    }
    fn create_row_new(
        &mut self
        ,row:u32
        ,activity:&Activity
        ,term_begin:&Term
        ,term_end:&Term
        ,fields:&Vec<KeyValue>
    ){
        let mut handles=Vec::new();

        let index=self.uuid.clone();
        handles.push(thread::spawn(move||{
            let mut index=index.write().unwrap();
            if let Ok(_)=index.resize_to(row){
                index.triee_mut().update(row,Uuid::new_v4().as_u128());
            }
        }));

        let activity=*activity as u8;
        let index=self.activity.clone();
        handles.push(thread::spawn(move||{
            let mut index=index.write().unwrap();
            if let Ok(_)=index.resize_to(row){
                index.triee_mut().update(row,activity);
            }
        }));

        let term_begin=if let Term::Overwrite(term_begin)=term_begin{
            *term_begin
        }else{
            chrono::Local::now().timestamp()
        };
        let index=self.term_begin.clone();
        handles.push(thread::spawn(move||{
            let mut index=index.write().unwrap();
            if let Ok(_)=index.resize_to(row){
                index.triee_mut().update(row,term_begin);
            }
        }));

        let term_end=if let Term::Overwrite(term_end)=term_end{
            *term_end
        }else{
            0
        };
        let index=self.term_end.clone();
        handles.push(thread::spawn(move||{
            let mut index=index.write().unwrap();
            if let Ok(_)=index.resize_to(row){
                index.triee_mut().update(row,term_end);
            }
        }));

        handles.append(&mut self.update_fields(row,fields));

        for h in handles{
            h.join().unwrap();
        }
    }

    pub fn update_row(&mut self,row:u32,activity:&Activity,term_begin:&Term,term_end:&Term,fields:&Vec<KeyValue>){
        let mut handles=Vec::new();

        handles.push(self.update_activity_async(row,*activity));
    
        handles.push(self.update_term_begin_async(row,if let Term::Overwrite(term_begin)=term_begin{
            *term_begin
        }else{
            chrono::Local::now().timestamp()
        }));

        handles.push(self.update_term_end_async(row,if let Term::Overwrite(term_end)=term_end{
            *term_end
        }else{
            0
        }));

        handles.append(&mut self.update_fields(row,fields));

        for h in handles{
            h.join().unwrap();
        }
    }
    
    fn last_update_now(&mut self,row:u32){
        self.last_updated.write().unwrap().update(row,chrono::Local::now().timestamp());
    } 
    fn update_activity_async(&mut self,row:u32,activity:Activity)->thread::JoinHandle<()>{
        let index=self.activity.clone();
        thread::spawn(move||{
            index.write().unwrap().update(row,activity as u8);
        })
    }
    pub fn update_activity(&mut self,row:u32,activity: Activity){
        let h=self.update_activity_async(row,activity);
        self.last_update_now(row);
        h.join().unwrap();
    }
    fn update_term_begin_async(&mut self,row:u32,from:i64)->thread::JoinHandle<()>{
        let index=self.term_begin.clone();
        thread::spawn(move||{
            index.write().unwrap().update(row,from);
        })
    }
    pub fn update_term_begin(&mut self,row:u32,from: i64){
        let h=self.update_term_begin_async(row,from);
        self.last_update_now(row);
        h.join().unwrap();
    }
    fn update_term_end_async(&mut self,row:u32,to:i64)->thread::JoinHandle<()>{
        let index=self.term_end.clone();
        thread::spawn(move||{
            index.write().unwrap().update(row,to);
        })
    }
    pub fn update_term_end(&mut self,row:u32,to: i64){
        let h=self.update_term_end_async(row,to);
        self.last_update_now(row);
        h.join().unwrap();
    }
    pub fn update_fields(&mut self,row:u32,fields:&Vec<KeyValue>)->Vec<thread::JoinHandle<()>>{
        let mut handles=Vec::new();
        for kv in fields.iter(){
            handles.push(self.update_field_async(row,&kv.key,&kv.value));
        }
        self.last_update_now(row);
        handles
    }
    pub fn update_field_async(&mut self,row:u32,field_name:&str,cont:&Vec<u8>)->thread::JoinHandle<()>{
        let field=if self.fields_cache.contains_key(field_name){
            self.fields_cache.get_mut(field_name).unwrap()
        }else{
            self.create_field(field_name)
        };
        let cont=cont.to_owned();
        let index=field.clone();
        thread::spawn(move||{
            index.write().unwrap().update(row,&cont).unwrap();
        })
    }
    pub fn update_field(&mut self,row:u32,field_name:&str,cont:&[u8]){
        let field=if self.fields_cache.contains_key(field_name){
            self.fields_cache.get_mut(field_name).unwrap()
        }else{
            self.create_field(field_name)
        };
        let index=field.clone();
        index.write().unwrap().update(row,cont).unwrap();
        self.last_update_now(row);
    }
    fn create_field(&mut self,field_name:&str)->&mut Arc<RwLock<FieldData>>{
        let dir_name=self.data_dir.to_string()+"/fields/"+field_name+"/";
        std::fs::create_dir_all(dir_name.to_owned()).unwrap();
        if std::path::Path::new(&dir_name).exists(){
            let field=FieldData::new(&dir_name).unwrap();
            self.fields_cache.entry(String::from(field_name)).or_insert(
                Arc::new(RwLock::new(field))
            );
        }
        self.fields_cache.get_mut(field_name).unwrap()
    }
    pub fn delete(&mut self,row:u32){
        let mut handles=Vec::new();
        let index=self.serial.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().delete(row);
        }));
        
        let index=self.uuid.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().delete(row);
        }));

        let index=self.activity.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().delete(row);
        }));

        let index=self.term_begin.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().delete(row);
        }));

        let index=self.term_end.clone();
        handles.push(thread::spawn(move||{
            index.write().unwrap().delete(row);
        }));

        self.load_fields();
        for (_,v) in &mut self.fields_cache{
            let index=v.clone();
            handles.push(thread::spawn(move||{
                index.write().unwrap().delete(row);
            }));
        }

        self.last_updated.write().unwrap().delete(row);

        for h in handles{
            h.join().unwrap();
        }
    }

    pub fn serial(&self,row:u32)->u32{
        if let Some(v)=self.serial.read().unwrap().index().value(row){
            v
        }else{
            0
        }
    }
    pub fn uuid(&self,row:u32)->u128{
        if let Some(v)=self.uuid.read().unwrap().value(row){
            v
        }else{
            0
        }
    }
    pub fn uuid_str(&self,row:u32)->String{
        if let Some(v)=self.uuid.read().unwrap().value(row){
            uuid::Uuid::from_u128(v).to_string()
        }else{
            "".to_string()
        }
    }
    pub fn activity(&self,row:u32)->Activity{
        if let Some(v)=self.activity.read().unwrap().value(row){
            if v!=0{
                Activity::Active
            }else{
                Activity::Inactive
            }
        }else{
            Activity::Inactive
        }
    }
    pub fn term_begin(&self,row:u32)->i64{
        if let Some(v)=self.term_begin.read().unwrap().value(row){
            v
        }else{
            0
        }
    }
    pub fn term_end(&self,row:u32)->i64{
        if let Some(v)=self.term_end.read().unwrap().value(row){
            v
        }else{
            0
        }
    }
    pub fn last_updated(&self,row:u32)->i64{
        if let Some(v)=self.last_updated.read().unwrap().value(row){
            v
        }else{
            0
        }
    }
    pub fn field_bytes(&self,row:u32,name:&str)->&[u8]{
        if let Some(f)=self.field(name){
            if let Some(v)=f.read().unwrap().get(row){
                v
            }else{
                b""
            }
        }else{
            b""
        }
    }
    pub fn field_num(&self,row:u32,name:&str)->f64{
        if let Some(f)=self.field(name){
            if let Some(f)=f.read().unwrap().num(row){
                f
            }else{
                0.0
            }
        }else{
            0.0
        }
    }

    pub fn fields(&self)->Vec<&String>{
        let mut fields=Vec::new();
        for (key,_) in &self.fields_cache{
            fields.push(key);
        }
        fields
    }
    pub fn load_fields(&mut self){
        let d=std::fs::read_dir(self.data_dir.to_string()+"/fields/").unwrap();
        for p in d{
            if let Ok(p)=p{
                let path=p.path();
                if path.is_dir(){
                    if let Some(fname)=path.file_name(){
                        if let Some(str_fname)=fname.to_str(){
                            if !self.fields_cache.contains_key(str_fname){
                                if let Some(p)=path.to_str(){
                                    let field=FieldData::new(&(p.to_string()+"/")).unwrap();
                                    self.fields_cache.entry(String::from(str_fname)).or_insert(
                                        Arc::new(RwLock::new(field))
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    pub fn field(&self,name:&str)->Option<&Arc<RwLock<FieldData>>>{
        self.fields_cache.get(name)
    }

    pub fn all(&self)->RowSet{
        self.serial.read().unwrap().index().triee().iter().map(|r|r.row()).collect()
    }
    pub fn begin_search(&self)->Search{
        Search::new(self)
    }
    pub fn search_field(&self,field_name:impl Into<String>,condition:search::Field)->Search{
        Search::new(self).search_field(field_name,condition)
    }
    pub fn search_activity(&self,condition:Activity)->Search{
        Search::new(self).search_activity(condition)
    }
    pub fn search_term(&self,condition:search::Term)->Search{
        Search::new(self).search_term(condition)
    }
    pub fn search_row(&self,condition:search::Number)->Search{
        Search::new(self).search_row(condition)
    }
    pub fn search_default(&self)->Search{
        Search::new(self).search_default()
    }
}