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
pub use analytics_next_sys as sys;
use gloo_utils::format::JsValueSerdeExt;
use serde_json::Value;
use std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::prelude::*;

#[derive(Clone)]
pub struct AnalyticsBrowser {
    pub instance: Rc<sys::AnalyticsBrowser>,
}

impl PartialEq for AnalyticsBrowser {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.instance, &other.instance)
    }
}

#[wasm_bindgen(getter_with_clone)]
pub struct Settings {
    #[wasm_bindgen(js_name = "writeKey")]
    pub write_key: String,
}

pub struct TrackingEvent<'a> {
    pub event: Cow<'a, str>,
    pub payload: Option<Value>,
    pub options: Option<Value>,
}

impl<'a> From<&'a str> for TrackingEvent<'a> {
    fn from(event: &'a str) -> Self {
        TrackingEvent {
            event: event.into(),
            payload: None,
            options: None,
        }
    }
}

impl From<String> for TrackingEvent<'static> {
    fn from(event: String) -> Self {
        TrackingEvent {
            event: event.into(),
            payload: None,
            options: None,
        }
    }
}

impl<'a> From<(&'a str, Value)> for TrackingEvent<'a> {
    fn from((event, payload): (&'a str, Value)) -> Self {
        TrackingEvent {
            event: event.into(),
            payload: Some(payload),
            options: None,
        }
    }
}

impl<'a> From<(&'a str, Option<Value>)> for TrackingEvent<'a> {
    fn from((event, payload): (&'a str, Option<Value>)) -> Self {
        TrackingEvent {
            event: event.into(),
            payload,
            options: None,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct User {
    pub id: Option<String>,
    pub traits: Value,
    pub options: Value,
}

impl AnalyticsBrowser {
    pub fn load(settings: Settings) -> Self {
        Self::load_with_options(settings, JsValue::UNDEFINED)
    }

    pub fn load_with_options(settings: Settings, options: JsValue) -> Self {
        let instance = sys::AnalyticsBrowser::new();
        instance.load(settings.into(), options);
        Self {
            instance: Rc::new(instance),
        }
    }

    pub fn identify(&self, user: impl Into<User>) {
        let user = user.into();
        let id = user.id.as_deref();
        let traits = JsValue::from_serde(&user.traits).unwrap_or(JsValue::NULL);
        let options = JsValue::from_serde(&user.options).unwrap_or(JsValue::NULL);

        self.instance.identify(id, traits, options);
    }

    pub fn track<'a>(&self, event: impl Into<TrackingEvent<'a>>) {
        let event = event.into();

        let name = &event.event;
        let properties = event
            .payload
            .and_then(|value| JsValue::from_serde(&value).ok())
            .unwrap_or(JsValue::UNDEFINED);
        let options = event
            .options
            .and_then(|value| JsValue::from_serde(&value).ok())
            .unwrap_or(JsValue::UNDEFINED);

        self.instance.track(name, properties, options);
    }

    #[must_use = "A tracking operation must be completed by calling the TrackBuilder::complete() function"]
    pub fn build(&self, event: impl Into<String>) -> TrackBuilder<'_> {
        let event = event.into();
        TrackBuilder {
            instance: &self.instance,
            event,
            properties: HashMap::new(),
            options: JsValue::UNDEFINED,
        }
    }

    pub fn page(&self) {
        self.instance.page();
    }
}

pub struct TrackBuilder<'a> {
    pub instance: &'a sys::AnalyticsBrowser,
    pub event: String,
    pub properties: HashMap<String, Value>,
    pub options: JsValue,
}

impl<'a> TrackBuilder<'a> {
    pub fn options(mut self, options: JsValue) -> Self {
        self.options = options;
        self
    }

    pub fn properties(mut self, properties: HashMap<String, Value>) -> Self {
        self.properties = properties;
        self
    }

    pub fn extend_properties(
        mut self,
        properties: impl IntoIterator<Item = (String, Value)>,
    ) -> Self {
        self.properties.extend(properties);
        self
    }

    pub fn add_property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }

    pub fn complete(self) {
        if let Ok(properties) = JsValue::from_serde(&self.properties) {
            self.instance.track(&self.event, properties, self.options);
        }
    }
}