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
use minijinja::value::{Enumerator, Object, Value};
use std::sync::Arc;

use super::Error;
use crate::{client::CoreClient, events::UtcDateTime};

/// Hold a User client
#[derive(Debug)]
pub struct UserValue {
    user_id: String,
    display_name: String,
    _client: Arc<CoreClient>,
}

impl UserValue {
    pub(crate) async fn new(client: Arc<CoreClient>) -> Result<Self, Error> {
        let c = client.client();
        let user_id = c
            .user_id()
            .ok_or(Error::Remap(
                "user".to_string(),
                "missing user_id".to_string(),
            ))?
            .to_string();
        let display_name = match c.account().get_display_name().await {
            Ok(Some(name)) => name,
            _ => user_id.clone(),
        };

        Ok(UserValue {
            user_id,
            display_name,
            _client: client,
        })
    }
}

impl Object for UserValue {
    fn get_value(self: &Arc<Self>, field: &Value) -> Option<Value> {
        match field.as_str() {
            Some("user_id") => Some(Value::from(self.user_id.clone())),
            Some("display_name") => Some(Value::from(self.display_name.clone())),
            _ => None,
        }
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Str(&["user_id", "display_name"])
    }
}

/// Reference
#[derive(Debug)]
pub struct ObjRef {
    id: String,
    obj_type: String,
}

impl ObjRef {
    pub(crate) fn new(id: String, obj_type: String) -> Self {
        ObjRef { id, obj_type }
    }
}

impl Object for ObjRef {
    fn get_value(self: &Arc<Self>, field: &Value) -> Option<Value> {
        match field.as_str() {
            Some("id") => Some(Value::from(self.id.clone())),
            Some("type") => Some(Value::from(self.obj_type.clone())),
            _ => None,
        }
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Str(&["id", "type"])
    }
}

/// Hold a UtcDateTime for templates
#[derive(Debug)]
pub struct UtcDateTimeValue {
    date: UtcDateTime,
}

impl UtcDateTimeValue {
    pub(crate) fn new(date: UtcDateTime) -> Self {
        UtcDateTimeValue { date }
    }
}

impl Object for UtcDateTimeValue {
    fn get_value(self: &Arc<Self>, field: &Value) -> Option<Value> {
        match field.as_str() {
            Some("as_timestamp") => Some(Value::from(self.date.timestamp())),
            Some("as_rfc3339") => Some(Value::from(self.date.to_rfc3339())),
            _ => None,
        }
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Str(&["as_timestamp"])
    }
}