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
575
576
577
//! Output data types for database queries.

/// To return results after processing queries for one document.
// *************************************************************************************************
#[derive(Debug, Clone)]
pub enum OutputDataOne {
    Doc(
        (
            Option<mongodb::bson::document::Document>,
            Vec<String>,
            std::collections::HashMap<String, String>,
            String,
            String,
        ),
    ),
}

impl OutputDataOne {
    /// Get raw document.
    /// Hint: For non-standard operations.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one(filter, None)?;
    /// if output_data.is_valid()? {
    ///     println!("{:?}", output_data.raw_doc()?);
    /// }
    /// ```
    ///
    pub fn raw_doc(&self) -> mongodb::bson::document::Document {
        match self {
            Self::Doc(data) => {
                if data.0.is_some() {
                    data.0.clone().unwrap()
                } else {
                    mongodb::bson::document::Document::new()
                }
            }
        }
    }

    /// Get prepared document.
    /// Hint: For page template.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one(filter, None)?;
    /// if output_data.is_valid()? {
    ///     println!("{:?}", output_data.doc()?);
    /// }
    /// ```
    ///
    pub fn doc(&self) -> Result<mongodb::bson::document::Document, Box<dyn std::error::Error>> {
        match self {
            Self::Doc(data) => {
                if data.0.is_some() {
                    Self::to_prepared_doc(
                        data.0.clone().unwrap(),
                        data.1.clone(),
                        data.2.clone(),
                        data.3.clone(),
                    )
                } else {
                    Ok(mongodb::bson::document::Document::new())
                }
            }
        }
    }

    /// Get json-line.
    /// Hint: For Ajax.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one(filter, None)?;
    /// if output_data.is_valid()? {
    ///     println!("{}", output_data.json()?);
    /// }
    /// ```
    ///
    pub fn json(&self) -> Result<String, Box<dyn std::error::Error>> {
        match self {
            Self::Doc(data) => {
                if data.0.is_some() {
                    Ok(mongodb::bson::Bson::Document(Self::to_prepared_doc(
                        data.0.clone().unwrap(),
                        data.1.clone(),
                        data.2.clone(),
                        data.3.clone(),
                    )?)
                    .into_relaxed_extjson()
                    .to_string())
                } else {
                    Ok(String::from("{}"))
                }
            }
        }
    }

    /// Get model instance.
    /// Hint: For the `save`, `update`, `delete` operations.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one(filter, None)?;
    /// if output_data.is_valid()? {
    ///     println!("{:?}", output_data.model::<UserProfile>()?);
    /// }
    /// ```
    ///
    pub fn model<T>(&self) -> Result<T, mongodb::bson::de::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        match self {
            Self::Doc(data) => {
                if data.0.is_some() {
                    let doc = Self::to_prepared_doc(
                        data.0.clone().unwrap(),
                        data.1.clone(),
                        data.2.clone(),
                        data.3.clone(),
                    )
                    .unwrap();
                    let ignore_fields = data.1.clone();
                    let map_widget_type = data.2.clone();
                    let mut prepared_doc = mongodb::bson::document::Document::new();
                    let bson_null = &mongodb::bson::Bson::Null;
                    for (field_name, widget_type) in map_widget_type {
                        if ignore_fields.contains(&field_name) {
                            continue;
                        }
                        let bson_val = doc.get(field_name.as_str()).unwrap();
                        if widget_type == "inputFile" || widget_type == "inputImage" {
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    let result = serde_json::to_string(
                                        &bson_val.clone().into_relaxed_extjson(),
                                    )
                                    .unwrap();
                                    mongodb::bson::Bson::String(result)
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else {
                            prepared_doc.insert(field_name, bson_val);
                        }
                    }
                    mongodb::bson::de::from_document::<T>(prepared_doc)
                } else {
                    let prepared_doc = mongodb::bson::document::Document::new();
                    mongodb::bson::de::from_document::<T>(prepared_doc)
                }
            }
        }
    }

    /// Get validation status (boolean)
    /// Hint: For check document availability.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one_and_delete(filter, None)?;
    /// if !routput_data.is_valid() {
    ///     println!("{}", routput_data.err_msg());
    /// }
    /// ```
    ///
    pub fn is_valid(&self) -> bool {
        match self {
            Self::Doc(data) => data.0.is_some(),
        }
    }

    /// A description of the error if the document was not deleted.
    /// (Main use for admin panel.)
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find_one_and_delete(filter, None)?;
    /// if !routput_data.is_valid() {
    ///     println!("{}", routput_data.err_msg());
    /// }
    /// ```
    ///
    pub fn err_msg(&self) -> String {
        match self {
            Self::Doc(data) => data.4.clone(),
        }
    }

    /// Get prepared doc.
    /// Hint: Converting data types to model-friendly formats.
    // ---------------------------------------------------------------------------------------------
    pub fn to_prepared_doc(
        doc: mongodb::bson::document::Document,
        ignore_fields: Vec<String>,
        map_widget_type: std::collections::HashMap<String, String>,
        model_name: String,
    ) -> Result<mongodb::bson::document::Document, Box<dyn std::error::Error>> {
        let bson_null = &mongodb::bson::Bson::Null;
        let mut prepared_doc = mongodb::bson::document::Document::new();
        for (field_name, widget_type) in map_widget_type {
            if ignore_fields.contains(&field_name) {
                continue;
            }
            if field_name == "hash" {
                let bson_val = doc.get("_id").unwrap();
                prepared_doc.insert(
                    field_name,
                    if bson_val != bson_null {
                        mongodb::bson::Bson::String(bson_val.as_object_id().unwrap().to_hex())
                    } else {
                        Err(format!(
                            "Model: `{}` > Field: `hash` > Method: `find_one()` : \
                                Missing document identifier `_id`.",
                            model_name.clone()
                        ))?
                    },
                );
            } else if widget_type == "inputPassword" {
                let bson_val = doc.get(field_name.as_str()).unwrap();
                prepared_doc.insert(
                    field_name,
                    if bson_val != bson_null {
                        mongodb::bson::Bson::String(String::new())
                    } else {
                        mongodb::bson::Bson::Null
                    },
                );
            } else if widget_type == "inputDate" {
                let bson_val = doc.get(field_name.as_str()).unwrap();
                prepared_doc.insert(
                    field_name,
                    if bson_val != bson_null {
                        mongodb::bson::Bson::String(
                            bson_val.as_datetime().unwrap().to_rfc3339()[..10].into(),
                        )
                    } else {
                        mongodb::bson::Bson::Null
                    },
                );
            } else if widget_type == "inputDateTime" {
                let bson_val = doc.get(field_name.as_str()).unwrap();
                prepared_doc.insert(
                    field_name,
                    if bson_val != bson_null {
                        mongodb::bson::Bson::String(
                            bson_val.as_datetime().unwrap().to_rfc3339()[..16].into(),
                        )
                    } else {
                        mongodb::bson::Bson::Null
                    },
                );
            } else {
                let bson_val = doc.get(field_name.as_str()).unwrap();
                prepared_doc.insert(field_name, bson_val);
            }
        }

        Ok(prepared_doc)
    }
}

/// To return results after processing queries for many documents.
// *************************************************************************************************
#[derive(Debug, Clone)]
pub enum OutputDataMany {
    Data(
        (
            Option<mongodb::bson::document::Document>,
            Option<mongodb::options::FindOptions>,
            mongodb::sync::Collection,
            Vec<String>,
            std::collections::HashMap<String, String>,
            String,
        ),
    ),
}

impl OutputDataMany {
    // Get raw documents.
    // Hint: For non-standard operations.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find(filter, None)?;
    /// if output_data.is_valid()? {
    ///     // Get raw documents. (Hint: For non-standard operations.)
    ///     println!("{:?}", routput_data.raw_docs()?);
    /// }
    /// ```
    ///
    pub fn raw_docs(
        &self,
    ) -> Result<Vec<mongodb::bson::document::Document>, Box<dyn std::error::Error>> {
        match self {
            Self::Data(data) => {
                let cursor = data.2.find(data.0.clone(), data.1.clone())?;
                Ok(cursor
                    .map(|item| item.unwrap())
                    .collect::<Vec<mongodb::bson::document::Document>>())
            }
        }
    }

    /// Get prepared documents.
    /// Hint: For page template.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find(filter, None)?;
    /// if output_data.is_valid()? {
    ///     // Get prepared documents. (Hint: For page template.)
    ///     println!("{:?}", routput_data.docs()?);
    /// }
    /// ```
    ///
    pub fn docs(
        &self,
    ) -> Result<Vec<mongodb::bson::document::Document>, Box<dyn std::error::Error>> {
        match self {
            Self::Data(data) => {
                let mut cursor = data.2.find(data.0.clone(), data.1.clone())?;
                let ignore_fields = data.3.clone();
                let bson_null = &mongodb::bson::Bson::Null;
                let mut docs: Vec<mongodb::bson::document::Document> = Vec::new();
                while let Some(doc) = cursor.next() {
                    let doc = doc?;
                    let map_widget_type = data.4.clone();
                    let mut prepared_doc = mongodb::bson::document::Document::new();
                    for (field_name, widget_type) in map_widget_type {
                        if ignore_fields.contains(&field_name) {
                            continue;
                        }
                        if field_name == "hash" {
                            let bson_val = doc.get("_id").unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_object_id().unwrap().to_hex(),
                                    )
                                } else {
                                    Err(format!(
                                        "Model: `{}` > Field: `hash` > Method: `find_one()` : \
                                        Missing document identifier `_id`.",
                                        data.5.clone()
                                    ))?
                                },
                            );
                        } else if widget_type == "inputPassword" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(String::new())
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else if widget_type == "inputDate" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_datetime().unwrap().to_rfc3339()[..10].into(),
                                    )
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else if widget_type == "inputDateTime" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_datetime().unwrap().to_rfc3339()[..16].into(),
                                    )
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(field_name, bson_val);
                        }
                    }
                    docs.push(prepared_doc);
                }

                Ok(docs)
            }
        }
    }

    /// Get json-line.
    /// Hint: For Ajax.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find(filter, None)?;
    /// if output_data.is_valid()? {
    ///     // Get json-line. (Hint: For Ajax.)
    ///     println!("{:?}", routput_data.json()?);
    /// }
    /// ```
    ///
    pub fn json(&self) -> Result<String, Box<dyn std::error::Error>> {
        match self {
            Self::Data(data) => {
                let mut cursor = data.2.find(data.0.clone(), data.1.clone())?;
                let ignore_fields = data.3.clone();
                let bson_null = &mongodb::bson::Bson::Null;
                let mut json_line = String::new();
                while let Some(doc) = cursor.next() {
                    let doc = doc?;
                    let map_widget_type = data.4.clone();
                    let mut prepared_doc = mongodb::bson::document::Document::new();
                    for (field_name, widget_type) in map_widget_type {
                        if ignore_fields.contains(&field_name) {
                            continue;
                        }
                        if field_name == "hash" {
                            let bson_val = doc.get("_id").unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_object_id().unwrap().to_hex(),
                                    )
                                } else {
                                    Err(format!(
                                        "Model: `{}` > Field: `hash` > Method: `find_one()` : \
                                        Missing document identifier `_id`.",
                                        data.5.clone()
                                    ))?
                                },
                            );
                        } else if widget_type == "inputPassword" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(String::new())
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else if widget_type == "inputDate" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_datetime().unwrap().to_rfc3339()[..10].into(),
                                    )
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else if widget_type == "inputDateTime" {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(
                                field_name,
                                if bson_val != bson_null {
                                    mongodb::bson::Bson::String(
                                        bson_val.as_datetime().unwrap().to_rfc3339()[..16].into(),
                                    )
                                } else {
                                    mongodb::bson::Bson::Null
                                },
                            );
                        } else {
                            let bson_val = doc.get(field_name.as_str()).unwrap();
                            prepared_doc.insert(field_name, bson_val);
                        }
                    }

                    json_line = format!(
                        "{},{}",
                        json_line,
                        mongodb::bson::Bson::Document(prepared_doc)
                            .into_relaxed_extjson()
                            .to_string(),
                    );
                }

                Ok(format!(
                    "[{}]",
                    if !json_line.is_empty() {
                        &json_line[1..]
                    } else {
                        ""
                    }
                ))
            }
        }
    }

    /// Get validation status (boolean)
    /// Hint: For check documents availability.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find(filter, None)?;
    /// if output_data.is_valid()? {
    ///     ...
    /// }
    /// ```
    ///
    pub fn is_valid(&self) -> Result<bool, Box<dyn std::error::Error>> {
        Ok(self.count()? > 0)
    }

    /// Get the number of documents.
    // ---------------------------------------------------------------------------------------------
    ///
    /// # Example:
    ///
    /// ```
    /// let filter = doc!{};
    /// let output_data  = UserProfile::find(filter, None)?;
    /// if output_data.is_valid()? {
    ///     println!("{}", routput_data.count()?);
    /// }
    /// ```
    ///
    pub fn count(&self) -> mongodb::error::Result<i64> {
        match self {
            Self::Data(data) => {
                let find_options = data.1.clone().unwrap();
                let mut options = mongodb::options::CountOptions::default();
                options.hint = find_options.hint;
                options.limit = find_options.limit;
                options.max_time = find_options.max_time;
                options.skip = find_options.skip;
                options.collation = find_options.collation;
                data.2.count_documents(data.0.clone(), Some(options))
            }
        }
    }
}