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
//! Base

pub mod linked_resource;
pub mod simple_resource;
pub mod simple_resource_linked;

use crate::grpc::server::{Id, IdList, Ids};
use crate::postgres::PsqlJsonValue;
use crate::{common::ArrErr, grpc::GrpcDataObjectType};
use core::fmt::Debug;
use log::error;
use std::collections::HashMap;
use tokio_postgres::types::Type as PsqlFieldType;
use uuid::Uuid;

/// Generic trait providing useful functions for our resources
pub trait Resource
where
    Self: Sized,
{
    /// Allows us to implement the resource definition used for simple insert and update queries
    fn get_definition() -> ResourceDefinition;

    /// This function should be implemented for the resources where applicable (example implementation can be found in the flight_plan module).
    fn get_enum_string_val(field: &str, value: i32) -> Option<String> {
        let _field = field;
        let _value = value;
        None
    }
    /// This function should be implemented for the resources where applicable (example implementation can be found in the flight_plan module).
    fn get_table_indices() -> Vec<String> {
        vec![]
    }
    /// Returns `true` if the given column name is part of the resource's combined id
    fn has_id_col(id_col: &str) -> bool {
        for col in Self::get_definition().get_psql_id_cols() {
            if col == id_col {
                return true;
            }
        }
        false
    }
    /// Returns the `psql_table` [String] value of the resource's [ResourceDefinition]
    fn get_psql_table() -> String {
        Self::get_definition().get_psql_table()
    }
}

/// Allows us to transform the gRPC `Object` structs into a generic object
pub trait ObjectType<T>
where
    Self: Resource,
    T: GrpcDataObjectType,
{
    /// Get [`ObjectType<T>`]'s `ids` field, to be implemented by trait implementor
    fn get_ids(&self) -> Option<HashMap<String, String>> {
        None
    }
    /// Get [`ObjectType<T>`]'s `data` field, to be implemented by trait implementor
    fn get_data(&self) -> Option<T> {
        None
    }
    /// Set [`ObjectType<T>`]'s `ids` field, to be implemented by trait implementor
    fn set_ids(&mut self, ids: HashMap<String, String>);
    /// Set [`ObjectType<T>`]'s `data` field, to be implemented by trait implementor
    fn set_data(&mut self, data: T);

    /// Returns [`ObjectType<T>`]'s `data` [`GrpcDataObjectType`] value
    ///
    /// # Errors
    ///
    /// Returns [`ArrErr`] if any of the provided `id` [`String`]s could not be converted to a valid [`Uuid`]
    /// Get `Object` `data` if set, returns [`ArrErr`] if no `data` is set
    fn try_get_data(&self) -> Result<T, ArrErr> {
        match self.get_data() {
            Some(data) => Ok(data),
            None => {
                let error = "No data provided for ObjectType<T>.".to_string();
                error!("(try_get_data) {}", error);
                Err(ArrErr::Error(error))
            }
        }
    }
    /// Returns [`ObjectType<T>`]'s `ids` [`HashMap<String, String>`] as [`HashMap<String, Uuid>`]
    ///
    /// # Errors
    ///
    /// Returns [`ArrErr`] if any of the provided `id` [`String`]s could not be converted to a valid [`Uuid`]
    fn try_get_uuids(&self) -> Result<HashMap<String, Uuid>, ArrErr> {
        match self.get_ids() {
            Some(ids) => {
                let mut result = HashMap::new();
                for (field, id) in ids {
                    let uuid = Uuid::parse_str(&id)?;
                    result.insert(field, uuid);
                }
                Ok(result)
            }
            None => {
                let error = format!(
                    "No ids configured for resource [{}].",
                    Self::get_psql_table()
                );
                error!("(try_get_uuids) {}", error);
                Err(ArrErr::Error(error))
            }
        }
    }
    /// Returns [`ObjectType<T>`]'s `id_field` value as [`Option<String>`] if found
    ///
    /// Returns [`None`] if `ids` is not set, or the `id_field` is not found as a key in the `ids` [`HashMap`]
    fn get_value_for_id_field(&self, id_field: &str) -> Option<String> {
        match self.get_ids() {
            Some(map) => map.get(id_field).cloned(),
            None => None,
        }
    }
}

/// struct object defining resource metadata
#[derive(Clone, Debug)]
pub struct ResourceDefinition {
    /// psql table corresponding to the resource
    pub psql_table: String,
    /// psql column names used to identify the unique resource in the database
    pub psql_id_cols: Vec<String>,
    /// resource fields definition
    pub fields: HashMap<String, FieldDefinition>,
}

impl ResourceDefinition {
    /// returns [`String`] value of the struct's `psql_table` field
    pub fn get_psql_table(&self) -> String {
        self.psql_table.clone()
    }

    /// returns [`Vec<String>`] value of the struct's `psql_table_ids` field
    pub fn get_psql_id_cols(&self) -> Vec<String> {
        self.psql_id_cols.clone()
    }

    /// returns [`bool`] true if the provided `field` key is found in the `fields` [`HashMap`]
    pub fn has_field(&self, field: &str) -> bool {
        self.fields.contains_key(field)
    }

    /// returns [`FieldDefinition`] if the provided `field` is found in the `fields` [`HashMap`]
    /// returns an [`ArrErr`] if the field does not exist
    pub fn try_get_field(&self, field: &str) -> Result<&FieldDefinition, ArrErr> {
        match self.fields.get(field) {
            Some(field) => Ok(field),
            None => Err(ArrErr::Error(format!(
                "Tried to get field [{}] for table [{}], but the field does not exist.",
                field, self.psql_table
            ))),
        }
    }
}

/// Generic resource wrapper struct used to implement our generic traits
#[derive(Clone, Debug)]
pub struct ResourceObject<T>
where
    T: GrpcDataObjectType + prost::Message,
{
    /// unique ids of the resource [`HashMap<String, String>`]
    pub ids: Option<HashMap<String, String>>,
    /// resource field data
    pub data: Option<T>,
    /// field mask used for update actions
    pub mask: Option<::prost_types::FieldMask>,
}
impl<T: GrpcDataObjectType + prost::Message> ObjectType<T> for ResourceObject<T>
where
    Self: Resource,
{
    fn get_ids(&self) -> Option<HashMap<String, String>> {
        self.ids.clone()
    }
    fn set_ids(&mut self, ids: HashMap<String, String>) {
        self.ids = Some(ids)
    }
    fn get_data(&self) -> Option<T> {
        self.data.clone()
    }
    fn set_data(&mut self, data: T) {
        self.data = Some(data)
    }
}

/// Field definition struct defining field properties
#[derive(Clone, Debug)]
pub struct FieldDefinition {
    /// [`PsqlFieldType`]
    pub field_type: PsqlFieldType,
    /// [`bool`] to set if field is mandatory in the database
    mandatory: bool,
    /// [`bool`] to set if field should not be exposed to gRPC object
    internal: bool,
    /// [`bool`] to set if field should be read only for clients
    read_only: bool,
    /// [`String`] option to provide a default value used during database inserts
    default: Option<String>,
}

impl FieldDefinition {
    /// Create a new [`FieldDefinition`] with provided field_type and mandatory setting
    pub fn new(field_type: PsqlFieldType, mandatory: bool) -> Self {
        Self {
            field_type,
            mandatory,
            internal: false,
            read_only: false,
            default: None,
        }
    }
    /// Create a new internal [`FieldDefinition`] with provided field_type and mandatory setting
    pub fn new_internal(field_type: PsqlFieldType, mandatory: bool) -> Self {
        Self {
            field_type,
            mandatory,
            internal: true,
            read_only: true,
            default: None,
        }
    }
    /// Create a new read_only [`FieldDefinition`] with provided field_type and mandatory setting
    pub fn new_read_only(field_type: PsqlFieldType, mandatory: bool) -> Self {
        Self {
            field_type,
            mandatory,
            internal: false,
            read_only: true,
            default: None,
        }
    }

    /// Returns [`bool`] mandatory
    pub fn is_mandatory(&self) -> bool {
        self.mandatory
    }
    /// Returns [`bool`] internal
    pub fn is_internal(&self) -> bool {
        self.internal
    }
    /// Returns [`bool`] internal
    pub fn is_read_only(&self) -> bool {
        self.read_only
    }

    /// Returns [`bool`] `true` if a `default` value has been provided for this field and `false`if not
    pub fn has_default(&self) -> bool {
        self.default.is_some()
    }
    /// Sets the `default` value using the given default [`String`]
    pub fn set_default(&mut self, default: String) -> Self {
        self.default = Some(default);
        self.clone()
    }
    /// Gets the `default` value for this field
    ///
    /// The function will panic if no default has been set. It's recommended to call
    /// [`has_default`](FieldDefinition::has_default) first, to determine if this function can be used or
    /// not
    pub fn get_default(&self) -> String {
        if self.has_default() {
            self.default.clone().unwrap_or_else(|| String::from("NULL"))
        } else {
            panic!("get_default called on a field without a default value");
        }
    }
}

impl TryFrom<Id> for Uuid {
    type Error = ArrErr;
    fn try_from(id: Id) -> Result<Self, ArrErr> {
        Uuid::try_parse(&id.id).map_err(ArrErr::UuidError)
    }
}
impl TryFrom<IdList> for Vec<Uuid> {
    type Error = ArrErr;
    fn try_from(list: IdList) -> Result<Self, ArrErr> {
        let mut uuid_list = vec![];
        for id in list.ids.iter() {
            uuid_list.push(Uuid::try_parse(id).map_err(ArrErr::UuidError)?);
        }
        Ok(uuid_list)
    }
}
impl TryFrom<Ids> for HashMap<String, Uuid> {
    type Error = ArrErr;
    fn try_from(ids: Ids) -> Result<Self, ArrErr> {
        let mut uuid_hash = HashMap::new();
        for id in ids.ids.iter() {
            uuid_hash.insert(
                id.field.clone(),
                Uuid::try_parse(&id.value).map_err(ArrErr::UuidError)?,
            );
        }
        Ok(uuid_hash)
    }
}
impl TryFrom<PsqlJsonValue> for Vec<u32> {
    type Error = ArrErr;
    fn try_from(json_value: PsqlJsonValue) -> Result<Self, ArrErr> {
        match json_value.value.as_array() {
            Some(arr) => {
                let iter = arr.iter();
                let mut vec: Vec<u32> = vec![];
                for val in iter {
                    vec.push(val.as_u64().ok_or(ArrErr::Error(format!(
                        "json_value did not contain array with u32: {}",
                        json_value.value
                    )))? as u32);
                }
                Ok(vec)
            }
            None => {
                let error = format!(
                    "Could not convert [PsqlJsonValue] to [Vec<u32>]: {:?}",
                    json_value
                );
                error!("(try_from) {}", error);
                Err(ArrErr::Error(error))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio_postgres::types::Type as PsqlFieldType;

    // FieldDefinition tests
    #[test]
    fn test_field_definition_new() {
        let field_type = PsqlFieldType::VARCHAR;
        let mandatory = true;
        let field_def = FieldDefinition::new(field_type.clone(), mandatory);

        assert_eq!(field_def.field_type, field_type);
        assert_eq!(field_def.is_mandatory(), mandatory);
        assert!(!field_def.is_internal());
        assert!(!field_def.is_read_only());
        assert!(!field_def.has_default());
    }

    #[test]
    fn test_field_definition_internal_field() {
        let field_type = PsqlFieldType::FLOAT8;
        let mandatory = false;
        let field_def = FieldDefinition::new_internal(field_type.clone(), mandatory);

        assert_eq!(field_def.field_type, field_type);
        assert_eq!(field_def.is_mandatory(), mandatory);
        assert!(field_def.is_internal());
        assert!(field_def.is_read_only());
        assert!(!field_def.has_default());
    }

    #[test]
    fn test_field_definition_read_only_field() {
        let field_type = PsqlFieldType::FLOAT8;
        let mandatory = false;
        let field_def = FieldDefinition::new_read_only(field_type.clone(), mandatory);

        assert_eq!(field_def.field_type, field_type);
        assert_eq!(field_def.is_mandatory(), mandatory);
        assert!(!field_def.is_internal());
        assert!(field_def.is_read_only());
        assert!(!field_def.has_default());
    }

    #[test]
    fn test_field_definition_set_default() {
        let field_type = PsqlFieldType::BOOL;
        let mandatory = true;
        let mut field_def = FieldDefinition::new(field_type, mandatory);

        assert!(!field_def.has_default());

        let default_value = "true".to_owned();
        field_def.set_default(default_value.clone());

        assert!(field_def.has_default());
        assert_eq!(field_def.get_default(), default_value);
    }

    #[test]
    #[should_panic(expected = "get_default called on a field without a default value")]
    fn test_field_definition_get_default_without_default() {
        let field_type = PsqlFieldType::TEXT;
        let mandatory = false;
        let field_def = FieldDefinition::new_internal(field_type, mandatory);

        field_def.get_default();
    }

    #[test]
    fn test_field_definition_get_default_with_default() {
        let field_type = PsqlFieldType::FLOAT4;
        let mandatory = false;
        let default_value = "3.14".to_owned();
        let mut field_def = FieldDefinition::new(field_type, mandatory);
        field_def.set_default(default_value.clone());

        assert_eq!(field_def.get_default(), default_value);
    }

    // ResourceDefinition tests
    #[test]
    fn test_resource_definition_get_psql_table() {
        let psql_table = "my_table".to_owned();
        let resource_def = ResourceDefinition {
            psql_table: psql_table.clone(),
            psql_id_cols: Vec::new(),
            fields: HashMap::new(),
        };

        assert_eq!(resource_def.get_psql_table(), psql_table);
    }

    #[test]
    fn test_resource_definition_get_psql_id_cols() {
        let psql_id_cols = vec!["id".to_owned(), "name".to_owned()];
        let resource_def = ResourceDefinition {
            psql_table: String::new(),
            psql_id_cols: psql_id_cols.clone(),
            fields: HashMap::new(),
        };

        assert_eq!(resource_def.get_psql_id_cols(), psql_id_cols);
    }

    #[test]
    fn test_resource_definition_has_field() {
        let field_name = "field1";
        let field_def = FieldDefinition::new(PsqlFieldType::TEXT, true);

        let mut fields = HashMap::new();
        fields.insert(field_name.to_owned(), field_def);

        let resource_def = ResourceDefinition {
            psql_table: String::new(),
            psql_id_cols: Vec::new(),
            fields,
        };

        assert!(resource_def.has_field(field_name));
        assert!(!resource_def.has_field("nonexistent_field"));
    }

    #[test]
    fn test_resource_definition_try_get_field() {
        let field_name = "field1";
        let field_def = FieldDefinition::new(PsqlFieldType::TEXT, true);

        let mut fields = HashMap::new();
        fields.insert(field_name.to_owned(), field_def.clone());

        let resource_def = ResourceDefinition {
            psql_table: String::from("test"),
            psql_id_cols: vec![String::from("test_id")],
            fields,
        };

        let result = resource_def.try_get_field(field_name);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), _field_def));

        let result = resource_def.try_get_field("nonexistent_field");
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            format!(
                "error: Tried to get field [nonexistent_field] for table [{}], but the field does not exist.", resource_def.get_psql_table()
            )
        );
    }
}