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
#![allow(dead_code)]

pub mod util;
pub mod observer;


use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::time::Duration;
use mongodb::{Collection, Cursor, Database, IndexModel};
use mongodb::bson::{doc, Document, to_document};
use mongodb::options::{
    DeleteOptions,
    DropIndexOptions,
    FindOneOptions,
    FindOptions,
    InsertOneOptions,
    ListIndexesOptions,
    UpdateOptions
};
use serde::de::DeserializeOwned;
use serde::{Serialize};
use mongodb::error::Result;
use mongodb::results::UpdateResult;
use crate::futures::StreamExt;
use crate::macros::{error, trace};
use crate::model::observer::Observer;
use crate::model::util::ModelTimestamps;
use crate::Spark;

// TODO: this must move to types module
type Id = mongodb::bson::Bson;
pub type MongodbResult<T> = Result<T>;

#[derive(Debug, Serialize)]
pub struct Model<'a, M>
{
    inner: Box<M>,
    #[serde(skip)]
    db: Arc<Database>,
    #[serde(skip)]
    collection_name: &'a str,
    #[serde(skip)]
    collection: Collection<M>,
}

impl<'a, T: 'a> Deref for Model<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, T: 'a> DerefMut for Model<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<'a, M> Model<'a, M>
where
    M: Default,
    M: Serialize,
    M: DeserializeOwned,
    M: Send,
    M: Sync,
    M: Unpin,
    M: Debug,
    M: ModelTimestamps,
    M: Observer<M>
{
    /// makes a model and stores the data and collection_name to creating collection object
    /// to store data into it
    ///
    /// # Arguments
    ///
    /// * `db`: you cna pass None , in this way model created by global spark connection , or you can pass your own database
    /// * `collection_name`:  it's collection name that we use in create collection object
    ///
    /// returns: Model<M>
    ///
    /// # Examples
    ///
    /// ```
    /// struct User{
    ///     name: String
    /// }
    /// let db = ...;
    /// let user_model = Model::<User>::new(Arc::clone(db) , "users");
    /// ```
    pub fn new(db: Option<&Arc<Database>>, collection_name: &'a str) -> Model<'a, M> {
        if let Some(database) = db {
            let collection = database.collection::<M>(collection_name);
            return Model {
                inner: Box::<M>::default(),
                db: database.clone(),
                collection_name,
                collection,
            };
        }
        // it panics if it's not initialized before use
        let database = Spark::get_db();
        let collection = database.collection::<M>(collection_name);
        Model {
            inner: Box::<M>::default(),
            db: database,
            collection_name,
            collection,
        }
    }

    /// saves the change , if the inner has some _id then it's update the existing unless
    /// it's create  new document 
    pub async fn save(&mut self, options: impl Into<Option<InsertOneOptions>>)
                      -> MongodbResult<Id>
    {
        self.inner.updated_at();
        let mut converted = to_document(&self.inner)?;
        if let Some(id) = converted.get("_id") {
            let owned_id = id.to_owned();
            let upsert = self.collection.update_one(
                doc! {
                    "_id" : id
                },
                doc! { "$set": &converted},
                None,
            ).await?;
            if upsert.modified_count >= 1 {
                // dispatch call
                // this must be pinned to handle recursive async call
                Box::pin(M::updated(self)).await?;

                return Ok(owned_id);
            };
        }
        converted.remove("_id");
        self.inner.created_at();

        let re = self.collection.insert_one(
            &*self.inner,
            options,
        ).await?;

        // dispatch observer
        // this must be pinned to handle recursive async call
        Box::pin(M::created(self)).await?;

        Ok(re.inserted_id)
    }
    pub async fn find_one(&mut self, doc: impl Into<Document>, options: impl Into<Option<FindOneOptions>>)
                          -> MongodbResult<Option<&mut Self>>
    {
        let result = self.collection.find_one(
            Some(doc.into()),
            options,
        ).await?;
        match result {
            Some(inner) => {
                self.fill(inner);
                Ok(
                    Some(
                        self
                    )
                )
            }
            None => Ok(None)
        }
    }

    /// this is raw update , and you can pass document or your model 
    /// # Examples
    /// ## with the raw doc
    ///  ```
    ///  let user_model = User::new_model(Some(&db));
    ///     let updated = user_model.update(
    ///         doc! {
    ///             "name": "Hossein",
    ///         },
    ///         doc! {
    ///            "$set": {
    ///                 "name": "Hossein 33"
    ///             }
    ///         },
    ///         None,
    ///     ).await.unwrap(); 
    /// ```
    /// ## with the model 
    /// let user_model = User::new_model(Some(&db));
    ///     let mut sample_user = User::default();
    ///     sample_user.name = "Hossein 33".to_string();
    ///     let updated = user_model.update(
    ///         &sample_user,
    ///        doc! {
    ///            "$set": {
    ///                "name": "Hossein 3355"
    ///            }
    ///        },
    ///        None,
    ///    ).await.unwrap();
    ///
    /// ## with_model_instance 
    ///     let mut user_model = User::new_model(Some(&db));
    ///    user_model.name = "Hossein 3355".to_string();
    ///    user_model.age = 58;
    ///    let updated = user_model.update(
    ///        &user_model,
    ///        doc! {
    ///            "$set": {
    ///                "name": "Hossein 325"
    ///            }
    ///        },
    ///        None,
    ///    ).await.unwrap();
    ///
    /// NOTE : updated observer doesn't execute in this method
    ///
    pub async fn update(&self, query: impl Into<Document>, doc: impl Into<Document>, options: impl Into<Option<UpdateOptions>>)
                        -> MongodbResult<UpdateResult>
    {
        self.collection.update_one(
            query.into(),
            doc.into(),
            options,
        ).await
    }

    pub async fn find(&self, filter: impl Into<Document>, options: impl Into<Option<FindOptions>>)
                      -> MongodbResult<Cursor<M>>
    {
        self.collection.find(
            Some(filter.into()),
            options,
        ).await
    }

    pub async fn find_and_collect(&self, filter: impl Into<Document>, options: impl Into<Option<FindOptions>>)
                                  -> MongodbResult<Vec<MongodbResult<M>>>
    {
        // TODO write this in other functions
        let converted = filter.into();
        let doc = if converted.is_empty() {
            None
        } else {
            Some(converted)
        };

        let future = self.collection.find(
            doc,
            options,
        ).await?;
        Ok(future.collect().await)
    }


    pub fn register_attributes(&self, attributes: Vec<&str>)
    {
        let mut attrs = attributes.iter().map(|attr| attr.to_string()).collect::<Vec<String>>();
        let max_time_to_drop = Some(Duration::from_secs(5));
        let (tx, _) = tokio::sync::oneshot::channel();
        let db = self.db.clone();
        let coll_name = self.collection_name.to_owned();
        trace!("Spawn task to register indexes");
        let register_attrs = async move {
            let coll = db.collection::<M>(&coll_name);
            let previous_indexes = coll.list_indexes(
                Some(
                    ListIndexesOptions::builder().max_time(
                        max_time_to_drop
                    ).build()
                )
            ).await;

            let mut keys_to_remove = Vec::new();

            if previous_indexes.is_ok() {
                let foreach_future = previous_indexes.unwrap().for_each(|pr| {
                    match pr {
                        Ok(index_model) => {
                            index_model.keys.iter().for_each(|key| {
                                if key.0 != "_id" {
                                    if let Some(pos) = attrs.iter().position(|k| k == key.0) {
                                        // means attribute exists in struct and database and not need to create it
                                        attrs.remove(pos);
                                    } else if let Some(rw) = &index_model.options {
                                        // means the attribute must remove because not exists in struct
                                        keys_to_remove.push(
                                            rw.name.clone()
                                        )
                                    }
                                }
                            });
                        }
                        Err(error) => {
                            error!(
                                "Can't unpack index model {error}"
                            );
                        }
                    }
                    futures::future::ready(())
                });
                foreach_future.await;
            }
            let attrs = attrs.iter()
                .map(|attr| {
                    let key = attr.to_string();
                    IndexModel::builder().keys(
                        doc! {
                                key : 1
                            }
                    ).build()
                }).collect::<Vec<IndexModel>>();

            for name in keys_to_remove {
                let key = name.as_ref().unwrap();
                let _ = coll.drop_index(key,
                                        Some(
                                            DropIndexOptions::builder().max_time(
                                                max_time_to_drop
                                            ).build()
                                        ),
                ).await;
            }
            if !attrs.is_empty() {
                let result = coll.create_indexes(
                    attrs,
                    None,
                ).await;
                if let Err(error) = result {
                    error!(
                            "Can't create indexes : {:?}" ,
                            error
                        );
                }
            }
        };

        let task = tokio::spawn(register_attrs);

        let wait_for_complete = async move {
            let _ = task.await;
            let _ = tx.send(());
        };

        tokio::task::spawn(wait_for_complete);
    }

    pub async fn delete(&mut self, query: impl Into<Document>, options: impl Into<Option<DeleteOptions>>) -> MongodbResult<u64> {
        let re = self.collection.delete_one(
            query.into(),
            options,
        ).await?.deleted_count;

        // dispatch observer
        // this must be pinned to handle recursive async call
        M::deleted(self).await?;

        Ok(re)
    }

    pub fn fill(&mut self, inner: M) {
        *self.inner = inner;
    }
}


impl<'a, M> Model<'a, M>
where
    M: Default,
    M: Serialize,
{
    /// this method takes the inner and gives you ownership of inner then
    /// replace it with default value
    pub fn take_inner(&mut self) -> M {
        std::mem::take(&mut *self.inner)
    }

    pub fn inner_ref(&self) -> &M {
        self.inner.as_ref()
    }

    pub fn inner_mut(&mut self) -> &mut M {
        self.inner.as_mut()
    }

    pub fn inner_to_doc(&self) -> MongodbResult<Document> {
        let re = to_document(&self.inner)?;
        Ok(re)
    }
}


// converts

impl<'a, M> From<Model<'a, M>> for Document
where
    M: Serialize,
{
    fn from(value: Model<M>) -> Self {
        mongodb::bson::to_document(&value.inner).unwrap()
    }
}

impl<'a, M> From<&Model<'a, M>> for Document
where
    M: Serialize,
{
    fn from(value: &Model<'a, M>) -> Self {
        mongodb::bson::to_document(&value.inner).unwrap()
    }
}

impl<'a, M> From<&mut Model<'a, M>> for Document
where
    M: Serialize,
{
    fn from(value: &mut Model<'a, M>) -> Self {
        mongodb::bson::to_document(&value.inner).unwrap()
    }
}