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
use std::borrow::Borrow;
use std::fmt::Debug;
use std::marker::PhantomData;
use bson::{Bson, Document};
use bson::oid::ObjectId;
use mongodb::{Collection, Database};
use mongodb::error::Error;
use mongodb::options::{FindOneOptions, FindOptions};
use opentelemetry::{Context, global, KeyValue};
use crate::document::document::BaseDocument;
use crate::document::pageable::{PageableRequest, PageableResponse};
use crate::repository::base_repository::Repository;
use async_trait::async_trait;
use opentelemetry::trace::{Span, TraceContextExt, Tracer};

pub struct MongoRepository<T: BaseDocument + Debug + serde::ser::Serialize  + for<'de> serde::Deserialize<'de> + Sync  + Send> {
    pub database: Database,
    pub x: PhantomData<T>,
    pub collection: Collection<T>
}

impl<T: BaseDocument + Debug + serde::ser::Serialize  + for<'de> serde::Deserialize<'de> + Sync  + Send> MongoRepository<T> {
    pub fn convert_bson_to_entity(&self, doc: Document) -> Result<T, Error> {
        match bson::from_bson(Bson::Document(doc)) {
            Ok(entity) => Ok(entity),
            Err(err) => {
                Err(Error::custom(err))
            }
        }
    }
}

#[async_trait]
impl<T: BaseDocument + Debug + serde::ser::Serialize  + for<'de> serde::Deserialize<'de> + Sync  + Send> Repository<T> for MongoRepository<T> {
    async fn save(&self, entity: T, ctx: Option<&Context>) -> Result<ObjectId, Error> {

        if let Some(u_ctx) = ctx {
            let mut span =
                global::tracer("opentelemetry").start_with_context("save", u_ctx);

            span.set_attribute(KeyValue::new("method", "save"));
            span.set_attribute(KeyValue::new("system", "mongodb"));

            u_ctx.with_span(span);
        }

        let result = match self.collection.insert_one(entity, None).await {
            Ok(res) => res,
            Err(e) => return Err(Error::custom(e)),
        };

        match result.inserted_id.as_object_id() {
            None => Err(Error::custom("could not get object id saved object..")),
            Some(oid) => Ok(oid),
        }
    }

    async fn save_many(&self, entities: Vec<T>, ctx: Option<&Context>) -> Result<Vec<ObjectId>, Error> {
        let mut ids:Vec<ObjectId> = vec![];

        for entity in entities {
            let saved = self.save(entity, ctx)
                .await?;

            ids.push(saved);
        };

        Ok(ids)
    }

    async fn get_all_pageable(&self, request: PageableRequest, ctx: Option<&Context>) -> Result<PageableResponse<T>, Error> {
        todo!()
    }

    async fn count_documents_in_collection(&self, ctx: Option<&Context>) -> Result<u64, Error> {
        todo!()
    }

    async fn find_by_id(&self, id: &str, ctx: Option<&Context>) -> Result<T, Error> {
        todo!()
    }

    async fn find_by_raw_id(&self, id: ObjectId, ctx: Option<&Context>) -> Result<T, Error> {
        todo!()
    }

    async fn find_by_ids(&self, ids: Vec<String>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
        todo!()
    }

    async fn find_by_raw_ids(&self, pids: Vec<ObjectId>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
        todo!()
    }

    async fn find_by_filter_and_options(&self, filter: Document, options: Option<FindOneOptions>, ctx: Option<&Context>) -> Result<T, Error> {
        todo!()
    }

    async fn find_all_by_filter_and_options(&self, filter: Document, options: Option<FindOptions>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
        todo!()
    }

    async fn update(&self, entity: &T, ctx: Option<&Context>) -> Result<ObjectId, Error> {
        todo!()
    }

    async fn delete(&self, pid: String, ctx: Option<&Context>) -> Result<(), Error> {
        todo!()
    }

    // async fn save_many(&self, entities: Vec<T>, ctx: Option<&Context>) -> Result<Vec<ObjectId>, Error> {
    //     println!("{:?}", entities);
    //     todo!()
    // }
    //
    // async fn get_all_pageable(&self, request: PageableRequest, ctx: Option<&Context>) -> Result<PageableResponse<T>, Error> {
    //     println!("{:?}", request);
    //     todo!()
    // }
    //
    // async fn count_documents_in_collection(&self, ctx: Option<&Context>) -> Result<u64, Error> {
    //     todo!()
    // }
    //
    // async fn find_by_id(&self, id: &str, ctx: Option<&Context>) -> Result<T, Error> {
    //     todo!()
    // }
    //
    // async fn find_by_raw_id(&self, id: ObjectId, ctx: Option<&Context>) -> Result<T, Error> {
    //     todo!()
    // }
    //
    // async fn find_by_ids(&self, ids: Vec<String>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
    //     todo!()
    // }
    //
    // async fn find_by_raw_ids(&self, pids: Vec<ObjectId>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
    //     todo!()
    // }
    //
    // async fn find_by_filter_and_options(&self, filter: Document, options: Option<FindOneOptions>, ctx: Option<&Context>) -> Result<T, Error> {
    //     todo!()
    // }
    //
    // async fn find_all_by_filter_and_options(&self, filter: Document, options: Option<FindOptions>, ctx: Option<&Context>) -> Result<Vec<T>, Error> {
    //     todo!()
    // }
    //
    // async fn update(&self, entity: &T, ctx: Option<&Context>) -> Result<ObjectId, Error> {
    //     todo!()
    // }
    //
    // async fn delete(&self, pid: String, ctx: Option<&Context>) -> Result<(), Error> {
    //     todo!()
    // }

}