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
use log::{debug, error, warn};
use serde::{Deserialize, Serialize};

use crate::three_part_topic::ThreePartTopic;

pub trait PlugDefinitionCommon<'a> {
    fn name(&'a self) -> &'a str;
    fn topic_str(&'a self) -> &'a str;
    fn topic(&'a self) -> &'a TetherOrCustomTopic;
    fn qos(&'a self) -> i32;
}

#[derive(Serialize, Deserialize, Debug)]
pub enum TetherOrCustomTopic {
    Tether(ThreePartTopic),
    Custom(String),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct InputPlugDefinition {
    name: String,
    topic: TetherOrCustomTopic,
    qos: i32,
}

impl PlugDefinitionCommon<'_> for InputPlugDefinition {
    fn name(&self) -> &str {
        &self.name
    }

    fn topic_str(&self) -> &str {
        match &self.topic {
            TetherOrCustomTopic::Custom(s) => {
                debug!("Plug named \"{}\" has custom topic \"{}\"", &self.name, &s);
                s
            }
            TetherOrCustomTopic::Tether(t) => {
                debug!(
                    "Plug named \"{}\" has Three Part topic \"{:?}\"",
                    &self.name, t
                );
                t.topic()
            }
        }
    }

    fn topic(&'_ self) -> &'_ TetherOrCustomTopic {
        &self.topic
    }

    fn qos(&self) -> i32 {
        self.qos
    }
}

impl InputPlugDefinition {
    pub fn new(name: &str, topic: TetherOrCustomTopic, qos: Option<i32>) -> InputPlugDefinition {
        InputPlugDefinition {
            name: String::from(name),
            topic,
            qos: qos.unwrap_or(1),
        }
    }

    /// Use the topic of an incoming message to check against the definition of an Input Plug.
    ///
    /// Due to the use of wildcard subscriptions, multiple topic strings might match a given
    /// Input Plug definition. e.g. `someRole/any/plugMessages` and `anotherRole/any/plugMessages`
    /// should both match on an Input Plug named `plugMessages` unless more specific Role and/or ID
    /// parts were specified in the Input Plug Definition.
    ///
    /// In the case where an Input Plug was defined with a completely manually-specified topic string,
    /// this function returns a warning and marks ANY incoming message as a valid match; the end-user
    /// developer is expected to match against topic strings themselves.
    pub fn matches(&self, incoming_topic: &TetherOrCustomTopic) -> bool {
        match incoming_topic {
            TetherOrCustomTopic::Tether(incoming_three_parts) => match &self.topic {
                TetherOrCustomTopic::Tether(my_tpt) => {
                    let matches_role =
                        my_tpt.role() == "+" || my_tpt.role().eq(incoming_three_parts.role());
                    let matches_id =
                        my_tpt.id() == "+" || my_tpt.id().eq(incoming_three_parts.id());
                    let matches_plug_name = my_tpt.plug_name() == "+"
                        || my_tpt.plug_name().eq(incoming_three_parts.plug_name());
                    debug!("Test match for plug named \"{}\" with def {:?} against {:?} => matches_role? {}, matches_id? {}, matches_plug_name? {}", &self.name, &self.topic, &incoming_three_parts, matches_role, matches_id, matches_plug_name);
                    matches_role && matches_id && matches_plug_name
                }
                TetherOrCustomTopic::Custom(my_custom_topic) => {
                    debug!(
                    "Custom/manual topic \"{}\" on Plug \"{}\" cannot be matched automatically; please filter manually for this",
                    &my_custom_topic,
                    self.name()
                );
                    if my_custom_topic.as_str() == "#"
                        || my_custom_topic.as_str() == incoming_three_parts.topic()
                    {
                        true
                    } else {
                        false
                    }
                }
            },
            TetherOrCustomTopic::Custom(incoming_custom) => match &self.topic {
                TetherOrCustomTopic::Custom(my_custom_topic) => {
                    if my_custom_topic.as_str() == "#"
                        || my_custom_topic.as_str() == incoming_custom.as_str()
                    {
                        true
                    } else {
                        warn!(
                            "Incoming topic \"{}\" is not a three-part topic",
                            &incoming_custom
                        );
                        false
                    }
                }
                TetherOrCustomTopic::Tether(_) => {
                    error!("Incoming is NOT Three Part Topic but this plug DOES have Three Part Topic; cannot decide match");
                    false
                }
            },
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct OutputPlugDefinition {
    name: String,
    topic: TetherOrCustomTopic,
    qos: i32,
    retain: bool,
}

impl PlugDefinitionCommon<'_> for OutputPlugDefinition {
    fn name(&'_ self) -> &'_ str {
        &self.name
    }

    fn topic_str(&self) -> &str {
        match &self.topic {
            TetherOrCustomTopic::Custom(s) => s,
            TetherOrCustomTopic::Tether(t) => t.topic(),
        }
    }

    fn topic(&'_ self) -> &'_ TetherOrCustomTopic {
        &self.topic
    }

    fn qos(&'_ self) -> i32 {
        self.qos
    }
}

impl OutputPlugDefinition {
    pub fn new(
        name: &str,
        topic: TetherOrCustomTopic,
        qos: Option<i32>,
        retain: Option<bool>,
    ) -> OutputPlugDefinition {
        OutputPlugDefinition {
            name: String::from(name),
            topic,
            qos: qos.unwrap_or(1),
            retain: retain.unwrap_or(false),
        }
    }

    pub fn retain(&self) -> bool {
        self.retain
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub enum PlugDefinition {
    InputPlug(InputPlugDefinition),
    OutputPlug(OutputPlugDefinition),
}

impl PlugDefinition {
    pub fn name(&self) -> &str {
        match self {
            PlugDefinition::InputPlug(p) => p.name(),
            PlugDefinition::OutputPlug(p) => p.name(),
        }
    }

    pub fn topic(&self) -> &str {
        match self {
            PlugDefinition::InputPlug(p) => p.topic_str(),
            PlugDefinition::OutputPlug(p) => p.topic_str(),
        }
    }

    pub fn matches(&self, topic: &TetherOrCustomTopic) -> bool {
        match self {
            PlugDefinition::InputPlug(p) => p.matches(topic),
            PlugDefinition::OutputPlug(_) => {
                error!("We don't check matches for Output Plugs");
                false
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use crate::{
        three_part_topic::{parse_plug_name, ThreePartTopic},
        InputPlugDefinition, PlugDefinitionCommon, TetherOrCustomTopic,
    };

    #[test]
    fn input_match_tpt() {
        let plug_def = InputPlugDefinition::new(
            "testPlug",
            TetherOrCustomTopic::Tether(ThreePartTopic::new_for_subscribe(
                "testPlug", None, None, None,
            )),
            None,
        );

        assert_eq!(&plug_def.name, "testPlug");
        assert_eq!(plug_def.topic_str(), "+/+/testPlug");
        assert_eq!(parse_plug_name("+/+/testPlug"), Some("testPlug"));
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "dummy", "any", "testPlug"
            )))
        );
        assert!(
            !plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "dummy",
                "any",
                "anotherPlug"
            )))
        );
        // assert!(!plug_def.matches(&TetherOrCustomTopic::Custom("dummy/any/anotherPlug".into())));
    }

    #[test]
    fn input_match_tpt_custom_role() {
        let plug_def = InputPlugDefinition::new(
            "customPlug",
            TetherOrCustomTopic::Tether(ThreePartTopic::new_for_subscribe(
                "customPlug",
                Some("customRole"),
                None,
                None,
            )),
            None,
        );

        assert_eq!(&plug_def.name, "customPlug");
        assert_eq!(plug_def.topic_str(), "customRole/+/customPlug");
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "customRole",
                "any",
                "customPlug"
            )))
        );
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "customRole",
                "andAnythingElse",
                "customPlug"
            )))
        );
        assert!(
            !plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "customRole",
                "any",
                "notMyPlug"
            )))
        ); // wrong incoming Plug N.into())ame
        assert!(
            !plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "someOtherRole",
                "any",
                "customPlug"
            )))
        ); // wrong incoming R.into())ole
    }

    #[test]
    fn input_match_custom_id() {
        let plug_def = InputPlugDefinition::new(
            "customPlug",
            TetherOrCustomTopic::Tether(ThreePartTopic::new_for_subscribe(
                "customPlug",
                None,
                Some("specificID"),
                None,
            )),
            None,
        );

        assert_eq!(&plug_def.name, "customPlug");
        assert_eq!(plug_def.topic_str(), "+/specificID/customPlug");
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "anyRole",
                "specificID",
                "customPlug"
            )))
        );
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "anotherRole",
                "specificID",
                "customPlug"
            )))
        ); // wrong incoming Role
        assert!(
            !plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "anyRole",
                "specificID",
                "notMyPlug"
            )))
        ); // wrong incoming Plug Name
        assert!(
            !plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "anyRole",
                "anotherID",
                "customPlug"
            )))
        ); // wrong incoming ID
    }

    #[test]
    fn input_match_both() {
        let plug_def = InputPlugDefinition::new(
            "customPlug",
            TetherOrCustomTopic::Tether(ThreePartTopic::new_for_subscribe(
                "customPlug",
                Some("specificRole"),
                Some("specificID"),
                None,
            )),
            None,
        );

        assert_eq!(&plug_def.name, "customPlug");
        assert_eq!(plug_def.topic_str(), "specificRole/specificID/customPlug");
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "specificRole",
                "specificID",
                "customPlug"
            )))
        );
        assert!(!plug_def.matches(&TetherOrCustomTopic::Custom(
            "specificRole/specificID/notMyPlug".into()
        ))); // wrong incoming Plug N.into())ame
        assert!(!plug_def.matches(&TetherOrCustomTopic::Custom(
            "specificRole/anotherID/customPlug".into()
        ))); // wrong incoming.into()) ID
        assert!(!plug_def.matches(&TetherOrCustomTopic::Custom(
            "anotherRole/anotherID/customPlug".into()
        ))); // wrong incoming R.into())ole
    }

    #[test]
    fn input_match_custom_topic() {
        let plug_def = InputPlugDefinition::new(
            "customPlug",
            TetherOrCustomTopic::Custom("one/two/three/four/five".into()), // not a standard Tether Three Part Topic
            None,
        );

        assert_eq!(plug_def.name(), "customPlug");
        // it will match on exactly the same topic:
        assert!(plug_def.matches(&TetherOrCustomTopic::Custom(
            "one/two/three/four/five".into()
        )));

        // it will NOT match on anything else:
        assert!(!plug_def.matches(&TetherOrCustomTopic::Custom("one/one/one/one/one".into())));
    }

    #[test]
    fn input_match_wildcard() {
        let plug_def = InputPlugDefinition::new(
            "everything",
            TetherOrCustomTopic::Custom("#".into()), // fully legal, but not a standard Three Part Topic
            None,
        );

        assert_eq!(plug_def.name(), "everything");

        // Standard TPT will match
        assert!(
            plug_def.matches(&TetherOrCustomTopic::Tether(ThreePartTopic::new(
                "any", "any", "plugName"
            )))
        );

        // Anything will match, even custom incoming
        assert!(plug_def.matches(&TetherOrCustomTopic::Custom(
            "one/two/three/four/five".into()
        )));
    }
}