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
//! # Caching.
//! Caching information about Models for speed up work.
//!
//! Trait:
//! `Caching` - Methods caching information about Models for speed up work.
//!
//! Methods:
//! `to_cache` - Add metadata and widgects map to cache.
//! `form_wig` - Get an widgets map for page template.
//! `form_json` - Get Form attributes in Json format for page templates.
//! `form_json_for_admin` - Json-line for admin panel.
//! `form_html` - Get Html Form of Model for page templates.
//! `get_cache_data_for_query` - Get cached Model data.
//! `db_update_dyn_widgets` - Accepts json-line to update data, for dynamic widgets.
//!

use crate::{
    forms::Widget,
    models::{Meta, ToModel},
    store::{FormCache, FORM_STORE, MONGODB_CLIENT_STORE},
};

/// Caching information about Models for speed up work.
// #################################################################################################
pub trait CachingModel: ToModel {
    /// Add metadata and widgects map to cache.
    // *********************************************************************************************
    fn to_cache() -> Result<(), Box<dyn std::error::Error>> {
        // Get a key to access Model data in the cache.
        let key: String = Self::key();
        // Get write access in cache.
        let mut form_store = FORM_STORE.write()?;
        // Create `FormCache` default and add map of widgets and metadata of model.
        let meta: Meta = Self::meta()?;
        // Get MongoDB client for current model.
        let client_store = MONGODB_CLIENT_STORE.read()?;
        let client_cache: &mongodb::sync::Client = client_store.get(&meta.db_client_name).unwrap();
        // Get a widget map.
        let mut map_widgets: std::collections::HashMap<String, Widget> = Self::widgets()?;
        // Enrich the widget map with values for dynamic widgets.
        Self::vitaminize(
            meta.project_name.as_str(),
            meta.unique_project_key.as_str(),
            meta.collection_name.as_str(),
            &client_cache,
            &mut map_widgets,
        )?;
        // Init new FormCache.
        let new_form_cache = FormCache {
            meta,
            map_widgets,
            ..Default::default()
        };
        // Save structure `FormCache` to store.
        form_store.insert(key, new_form_cache);
        //
        Ok(())
    }

    /// Get an widgets map for page template.
    // *********************************************************************************************
    ///
    /// # Example:
    ///
    /// ```
    /// let widgets_map = UserProfile::form_wig()?;
    /// println!("{:?}", widgets_map);
    /// ```
    ///
    fn form_wig() -> Result<std::collections::HashMap<String, Widget>, Box<dyn std::error::Error>> {
        // Get a key to access Model data in the cache.
        let key: String = Self::key();
        // Get read access from cache.
        let mut form_store = FORM_STORE.read()?;
        // Check if there is metadata for the Model in the cache.
        if !form_store.contains_key(key.as_str()) {
            // Unlock.
            drop(form_store);
            // Add metadata and widgects map to cache.
            Self::to_cache()?;
            // Reaccess.
            form_store = FORM_STORE.read()?;
        }
        // Get data and return the result.
        if let Some(form_cache) = form_store.get(key.as_str()) {
            Ok(form_cache.map_widgets.clone())
        } else {
            let meta = Self::meta()?;
            Err(format!(
                "Model: `{}` -> Method: `form_wig()` : Failed to get data from cache.",
                meta.model_name
            ))?
        }
    }

    /// Get Form attributes in Json format for page templates.
    // *********************************************************************************************
    ///
    /// # Example:
    ///
    /// ```
    /// let json_line = UserProfile::form_json()?;
    /// println!("{}", json_line);
    /// ```
    ///
    fn form_json() -> Result<String, Box<dyn std::error::Error>> {
        // Get a key to access Model data in the cache.
        let key: String = Self::key();
        // Get read access from cache.
        let mut form_store = FORM_STORE.read()?;
        // Check if there is metadata for the Model in the cache.
        if !form_store.contains_key(key.as_str()) {
            // Unlock.
            drop(form_store);
            // Add metadata and widgects map to cache.
            Self::to_cache()?;
            // Reaccess.
            form_store = FORM_STORE.read()?;
        }
        // Generate data and return the result.
        if let Some(form_cache) = form_store.get(key.as_str()) {
            if form_cache.form_json.is_empty() {
                drop(form_store);
                let mut form_store = FORM_STORE.write()?;
                let form_cache = form_store.get(key.as_str()).unwrap();
                let json = serde_json::to_string(&form_cache.map_widgets.clone())?;
                let mut new_form_cache = form_cache.clone();
                new_form_cache.form_json = json.clone();
                form_store.insert(key, new_form_cache);
                return Ok(json);
            }
            Ok(form_cache.form_json.clone())
        } else {
            let meta = Self::meta()?;
            Err(format!(
                "Model: `{}` -> Method: `form_json()` : Failed to get data from cache.",
                meta.model_name
            ))?
        }
    }

    /// Json-line for admin panel.
    /// ( converts a widget map to a list, in the order of the Model fields )
    // *********************************************************************************************
    ///
    /// # Example:
    ///
    /// ```
    /// let json_line = UserProfile::form_json_for_admin()?;
    /// println!("{}", json_line);
    /// ```
    ///
    fn form_json_for_admin() -> Result<String, Box<dyn std::error::Error>> {
        // Get cached Model data.
        let (form_cache, _client_cache) = Self::get_cache_data_for_query()?;
        // Get Model metadata.
        let meta: Meta = form_cache.meta;
        let map_widgets = form_cache.map_widgets.clone();
        let mut widget_list: Vec<Widget> = Vec::new();
        // Get a list of widgets in the order of the model fields.
        for field_name in meta.fields_name.iter() {
            let widget = map_widgets.get(field_name).unwrap().clone();
            widget_list.push(widget);
        }
        //
        Ok(serde_json::to_string(&widget_list)?)
    }

    /// Get Html Form of Model for page templates.
    // *********************************************************************************************
    ///
    /// # Example:
    ///
    /// ```
    /// let html = UserProfile::form_html()?;
    /// println!("{}", html);
    /// ```
    ///
    fn form_html() -> Result<String, Box<dyn std::error::Error>> {
        // Get a key to access Model data in the cache.
        let key: String = Self::key();
        // Get read access from cache.
        let mut form_store = FORM_STORE.read()?;
        // Check if there is metadata for the Model in the cache.
        if !form_store.contains_key(key.as_str()) {
            // Unlock.
            drop(form_store);
            // Add metadata and widgects map to cache.
            Self::to_cache()?;
            // Reaccess.
            form_store = FORM_STORE.read()?;
        }
        // Generate data and return the result.
        if let Some(form_cache) = form_store.get(key.as_str()) {
            if form_cache.form_html.is_empty() {
                drop(form_store);
                let mut form_store = FORM_STORE.write()?;
                let form_cache = form_store.get(key.as_str()).unwrap();
                let html =
                    Self::to_html(&form_cache.meta.fields_name, form_cache.map_widgets.clone());
                let mut new_form_cache = form_cache.clone();
                new_form_cache.form_html = html.clone();
                form_store.insert(key, new_form_cache);
                return Ok(html);
            }
            Ok(form_cache.form_html.clone())
        } else {
            let meta = Self::meta()?;
            Err(format!(
                "Model: `{}` -> Method: `form_html()` : Failed to get data from cache.",
                meta.model_name
            ))?
        }
    }

    /// Get cached Model data.
    // *********************************************************************************************
    ///
    /// # Example:
    ///
    /// ```
    /// let (form_cache, client_cache) = UserProfile::get_cache_data_for_query()?;
    /// println!("{:?}", form_cache);
    /// ```
    ///
    fn get_cache_data_for_query(
    ) -> Result<(FormCache, mongodb::sync::Client), Box<dyn std::error::Error>> {
        // Get a key to access Model data in the cache.
        let key: String = Self::key();
        // Get read access from cache.
        let mut form_store = FORM_STORE.read()?;
        // Check if there is metadata for the Model in the cache.
        if !form_store.contains_key(key.as_str()) {
            // Unlock.
            drop(form_store);
            // Add metadata and widgects map to cache.
            Self::to_cache()?;
            // Reaccess.
            form_store = FORM_STORE.read()?;
        }
        // Generate data and return the result.
        if let Some(form_cache) = form_store.get(key.as_str()) {
            // Get model metadata from cache.
            let meta: &Meta = &form_cache.meta;
            // Get MongoDB client for current model.
            let client_store = MONGODB_CLIENT_STORE.read()?;
            let client: &mongodb::sync::Client = client_store.get(&meta.db_client_name).unwrap();
            //
            Ok((form_cache.clone(), client.clone()))
        } else {
            let meta = Self::meta()?;
            Err(format!(
                "Model: `{}` -> Method: `get_cache_data_for_query()` : Failed to get data from cache.",
                meta.model_name
            ))?
        }
    }

    /// Accepts json-line to update data, for dynamic widgets.
    /// Hint: Used in conjunction with the admin panel.
    ///
    /// # Example:
    ///
    /// ```
    /// let json-line =  r#"{"field_name":[["value","Title"]]}"#;
    /// // or
    /// let json-line = r#"{
    ///        "field_name":[["value","Title"]],
    ///        "field_name_2":[["value","Title 2"]],
    ///        "field_name_3":[["value","Title 3"]]
    ///     }"#;
    ///
    /// assert!(Dynamic::db_update_dyn_widgets(json-line).is_ok());
    /// ```
    ///
    // *********************************************************************************************
    fn db_update_dyn_widgets(json_line: &str) -> Result<(), Box<dyn std::error::Error>> {
        // Refresh the state in the technical database.
        // -----------------------------------------------------------------------------------------
        // Validation json-line.
        let re = regex::RegexBuilder::new(r#"^\{[\s]*(?:"[a-z][a-z\d]*(?:_[a-z\d]+)*":(?:\[(?:(?:\["[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+","[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+"\])(?:,\["[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+","[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+"\])*)*\]))(?:,[\s]*"[a-z][a-z\d]*(?:_[a-z\d]+)*":(?:\[(?:(?:\["[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+","[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+"\])(?:,\["[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+","[-_.,`@#$%^&+=*!~)(:><?;№|\\/\s\w]+"\])*)*\]))*[\s]*\}$"#)
            .case_insensitive(true)
            .build()
            .unwrap();
        if !re.is_match(json_line) {
            Err(format!(
                r#"Model: {} > Method: `db_update_dyn_widgets()` : \
                   The `json_line` parameter was not validation. \
                   Example: {{"field_name":[["value","Title"]]}}"#,
                Self::meta()?.model_name
            ))?
        }

        // Get cached Model data.
        let (form_cache, client_cache) = Self::get_cache_data_for_query()?;
        // Get Model metadata.
        let meta: Meta = form_cache.meta;
        let mango_tech_keyword = format!(
            "mango_tech__{}__{}",
            meta.project_name.clone(),
            meta.unique_project_key.clone()
        );
        let db = client_cache.database(&mango_tech_keyword);
        let coll = db.collection("dynamic_widgets");
        let query = mongodb::bson::doc! {
            "database": meta.database_name.clone(),
            "collection": meta.collection_name.clone()
        };
        let new_dyn_data: serde_json::Value = serde_json::from_str(json_line)?;
        let new_dyn_data =
            serde_json::from_value::<mongodb::bson::document::Document>(new_dyn_data)?;
        let mut curr_dyn_date = coll.find_one(query.clone(), None)?.unwrap();
        let dyn_date = curr_dyn_date.get_document_mut("fields").unwrap();

        for (field_name, bson_val) in new_dyn_data {
            dyn_date.insert(field_name.as_str(), bson_val);
        }

        let update = mongodb::bson::doc! {
            "$set": { "fields": dyn_date.clone() }
        };
        coll.update_one(query, update, None)?;

        // Clean up orphaned (if any) data.
        // -----------------------------------------------------------------------------------------
        let db = client_cache.database(meta.database_name.as_str());
        let coll = db.collection(meta.collection_name.as_str());
        let mut cursor = coll.find(None, None)?;
        // Iterate over all documents in the collection.
        while let Some(db_doc) = cursor.next() {
            let mut is_changed = false;
            let mut curr_doc = db_doc.clone()?;
            // Iterate over all fields in the document.
            for (field_name, widget_type) in meta.map_widget_type.clone() {
                // Choosing the only dynamic widgets.
                if widget_type.contains("Dyn") {
                    if curr_doc.is_null(field_name.as_str()) {
                        continue;
                    }
                    // Get a list of values to match.
                    let dyn_vec: Vec<String> = dyn_date
                        .get_array(field_name.as_str())?
                        .iter()
                        .map(|item| item.as_array().unwrap()[0].as_str().unwrap().to_string())
                        .collect();
                    // Selecting widgets with multi-selection support.
                    if widget_type.contains("Mult") {
                        let mut new_arr_bson = Vec::<mongodb::bson::Bson>::new();
                        if widget_type.contains("Text") {
                            let arr_bson = curr_doc.get_array(field_name.as_str())?;
                            new_arr_bson = arr_bson
                                .iter()
                                .map(|item| item.clone())
                                .filter(|item| {
                                    dyn_vec.contains(&item.as_str().unwrap().to_string())
                                })
                                .collect();
                            if new_arr_bson != *arr_bson {
                                is_changed = true;
                            }
                        } else if widget_type.contains("I32") {
                            let arr_bson = curr_doc.get_array(field_name.as_str())?;
                            new_arr_bson = arr_bson
                                .iter()
                                .map(|item| item.clone())
                                .filter(|item| {
                                    dyn_vec.contains(&item.as_i32().unwrap().to_string())
                                })
                                .collect();
                            if new_arr_bson != *arr_bson {
                                is_changed = true;
                            }
                        } else if widget_type.contains("U32") || widget_type.contains("I64") {
                            let arr_bson = curr_doc.get_array(field_name.as_str())?;
                            new_arr_bson = arr_bson
                                .iter()
                                .map(|item| item.clone())
                                .filter(|item| {
                                    dyn_vec.contains(&item.as_i64().unwrap().to_string())
                                })
                                .collect();
                            if new_arr_bson != *arr_bson {
                                is_changed = true;
                            }
                        } else if widget_type.contains("F64") {
                            let arr_bson = curr_doc.get_array(field_name.as_str())?;
                            new_arr_bson = arr_bson
                                .iter()
                                .map(|item| item.clone())
                                .filter(|item| {
                                    dyn_vec.contains(&item.as_f64().unwrap().to_string())
                                })
                                .collect();
                            if new_arr_bson != *arr_bson {
                                is_changed = true;
                            }
                        }
                        if is_changed {
                            if !new_arr_bson.is_empty() {
                                curr_doc
                                    .insert(field_name, mongodb::bson::Bson::Array(new_arr_bson));
                            } else {
                                curr_doc.insert(field_name, mongodb::bson::Bson::Null);
                            }
                        }
                    } else {
                        let mut val = String::new();
                        // Select widgets with support for one selection.
                        if widget_type.contains("Text") {
                            val = curr_doc.get_str(field_name.as_str())?.to_string();
                        } else if widget_type.contains("I32") {
                            val = curr_doc.get_i32(field_name.as_str())?.to_string();
                        } else if widget_type.contains("U32") || widget_type.contains("I64") {
                            val = curr_doc.get_i64(field_name.as_str())?.to_string();
                        } else if widget_type.contains("F64") {
                            val = curr_doc.get_f64(field_name.as_str())?.to_string();
                        }
                        if !dyn_vec.contains(&val) {
                            curr_doc.insert(field_name, mongodb::bson::Bson::Null);
                            is_changed = true;
                        }
                    }
                }
            }
            if is_changed {
                // Update values for dynamic widgets.
                // ---------------------------------------------------------------------------------
                let query = mongodb::bson::doc! {"_id": curr_doc.get_object_id("_id")?};
                coll.update_one(query, curr_doc, None)?;
            }
        }

        // Update metadata and widgects map to cache.
        // -----------------------------------------------------------------------------------------
        Self::to_cache()?;
        //
        Ok(())
    }
}