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
482
483
484
485
486
487
488
489
490
491
use request::notification::{NotificationBuilder, NotificationOptions};
use request::payload::{APSAlert, Payload, APS};

use std::{
    collections::BTreeMap,
    borrow::Cow,
};

#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct LocalizedAlert<'a> {
    title: &'a str,
    body: &'a str,

    #[serde(skip_serializing_if = "Option::is_none")]
    title_loc_key: Option<&'a str>,

    #[serde(skip_serializing_if = "Option::is_none")]
    title_loc_args: Option<Vec<Cow<'a, str>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    action_loc_key: Option<&'a str>,

    #[serde(skip_serializing_if = "Option::is_none")]
    loc_key: Option<&'a str>,

    #[serde(skip_serializing_if = "Option::is_none")]
    loc_args: Option<Vec<Cow<'a, str>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    launch_image: Option<&'a str>,
}

/// A builder to create a localized APNs payload.
///
/// # Example
///
/// ```rust
/// # extern crate a2;
/// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
/// # fn main() {
/// let mut builder = LocalizedNotificationBuilder::new("Hi there", "What's up?");
/// builder.set_badge(420);
/// builder.set_category("cat1");
/// builder.set_sound("prööt");
/// builder.set_mutable_content();
/// builder.set_action_loc_key("PLAY");
/// builder.set_launch_image("foo.jpg");
/// builder.set_loc_args(&["argh", "narf"]);
/// builder.set_title_loc_key("STOP");
/// builder.set_title_loc_args(&["herp", "derp"]);
/// builder.set_loc_key("PAUSE");
/// builder.set_loc_args(&["narf", "derp"]);
/// let payload = builder.build("device_id", Default::default())
///   .to_json_string().unwrap();
/// # }
/// ```
pub struct LocalizedNotificationBuilder<'a> {
    alert: LocalizedAlert<'a>,
    badge: Option<u32>,
    sound: Option<&'a str>,
    category: Option<&'a str>,
    mutable_content: u8,
}

impl<'a> LocalizedNotificationBuilder<'a> {
    /// Creates a new builder with the minimum amount of content.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let payload = LocalizedNotificationBuilder::new("a title", "a body")
    ///     .build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn new(
        title: &'a str,
        body: &'a str
    ) -> LocalizedNotificationBuilder<'a>
    {
        LocalizedNotificationBuilder {
            alert: LocalizedAlert {
                title: title,
                body: body,
                title_loc_key: None,
                title_loc_args: None,
                action_loc_key: None,
                loc_key: None,
                loc_args: None,
                launch_image: None,
            },
            badge: None,
            sound: None,
            category: None,
            mutable_content: 0,
        }
    }

    /// A number to show on a badge on top of the app icon.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_badge(4);
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\"},\"badge\":4,\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_badge(&mut self, badge: u32) -> &mut Self
    {
        self.badge = Some(badge);
        self
    }

    /// File name of the custom sound to play when receiving the notification.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_sound("ping");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\"},\"mutable-content\":0,\"sound\":\"ping\"}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_sound(&mut self, sound: &'a str) -> &mut Self
    {
        self.sound = Some(sound);
        self
    }

    /// When a notification includes the category key, the system displays the
    /// actions for that category as buttons in the banner or alert interface.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_category("cat1");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\"},\"category\":\"cat1\",\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_category(&mut self, category: &'a str) -> &mut Self
    {
        self.category = Some(category.into());
        self
    }

    /// The localization key for the notification title.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_title_loc_key("play");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\",\"title-loc-key\":\"play\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_title_loc_key(&mut self, key: &'a str) -> &mut Self
    {
        self.alert.title_loc_key = Some(key);
        self
    }

    /// Arguments for the title localization.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_title_loc_args(&["foo", "bar"]);
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\",\"title-loc-args\":[\"foo\",\"bar\"]},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_title_loc_args<S>(
        &mut self,
        args: &'a [S]
    ) -> &mut Self
    where
        S: Into<Cow<'a, str>> + AsRef<str>
    {
        let converted = args
            .iter()
            .map(|a| a.as_ref().into())
            .collect();

        self.alert.title_loc_args = Some(converted);
        self
    }

    /// The localization key for the action.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_action_loc_key("stop");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"action-loc-key\":\"stop\",\"body\":\"a body\",\"title\":\"a title\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_action_loc_key(&mut self, key: &'a str) -> &mut Self
    {
        self.alert.action_loc_key = Some(key);
        self
    }

    /// The localization key for the push message body.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_loc_key("lol");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"loc-key\":\"lol\",\"title\":\"a title\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_loc_key(&mut self, key: &'a str) -> &mut Self
    {
        self.alert.loc_key = Some(key);
        self
    }

    /// Arguments for the content localization.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_loc_args(&["omg", "foo"]);
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"loc-args\":[\"omg\",\"foo\"],\"title\":\"a title\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_loc_args<S>(
        &mut self,
        args: &'a [S]
    ) -> &mut Self
    where
        S: Into<Cow<'a, str>> + AsRef<str>
    {
        let converted = args
            .iter()
            .map(|a| a.as_ref().into())
            .collect();

        self.alert.loc_args = Some(converted);
        self
    }

    /// Image to display in the rich notification.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_launch_image("cat.png");
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"launch-image\":\"cat.png\",\"title\":\"a title\"},\"mutable-content\":0}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_launch_image(&mut self, image: &'a str) -> &mut Self
    {
        self.alert.launch_image = Some(image);
        self
    }

    /// Allow client to modify push content before displaying.
    ///
    /// ```rust
    /// # extern crate a2;
    /// # extern crate serde;
    /// # use a2::request::notification::{LocalizedNotificationBuilder, NotificationBuilder};
    /// # fn main() {
    /// let mut builder = LocalizedNotificationBuilder::new("a title", "a body");
    /// builder.set_mutable_content();
    /// let payload = builder.build("token", Default::default());
    ///
    /// assert_eq!(
    ///     "{\"aps\":{\"alert\":{\"body\":\"a body\",\"title\":\"a title\"},\"mutable-content\":1}}",
    ///     &payload.to_json_string().unwrap()
    /// );
    /// # }
    /// ```
    pub fn set_mutable_content(&mut self) -> &mut Self
    {
        self.mutable_content = 1;
        self
    }
}

impl<'a> NotificationBuilder<'a> for LocalizedNotificationBuilder<'a> {
    fn build(self, device_token: &'a str, options: NotificationOptions<'a>) -> Payload<'a>
    {
        Payload {
            aps: APS {
                alert: Some(APSAlert::Localized(self.alert)),
                badge: self.badge,
                sound: self.sound,
                content_available: None,
                category: self.category,
                mutable_content: Some(self.mutable_content),
            },
            device_token: device_token,
            options: options,
            data: BTreeMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_localized_notification_with_minimal_required_values() {
        let payload = LocalizedNotificationBuilder::new("the title", "the body")
            .build("device-token", Default::default())
            .to_json_string()
            .unwrap();

        let expected_payload = json!({
            "aps": {
                "alert": {
                    "title": "the title",
                    "body": "the body",
                },
                "mutable-content": 0
            }
        }).to_string();

        assert_eq!(expected_payload, payload);
    }

    #[test]
    fn test_localized_notification_with_full_data() {
        let mut builder = LocalizedNotificationBuilder::new("the title", "the body");

        builder.set_badge(420);
        builder.set_category("cat1");
        builder.set_sound("prööt");
        builder.set_mutable_content();
        builder.set_action_loc_key("PLAY");
        builder.set_launch_image("foo.jpg");
        builder.set_loc_args(&["argh", "narf"]);
        builder.set_title_loc_key("STOP");
        builder.set_title_loc_args(&["herp", "derp"]);
        builder.set_loc_key("PAUSE");
        builder.set_loc_args(&["narf", "derp"]);

        let payload = builder
            .build("device-token", Default::default())
            .to_json_string()
            .unwrap();

        let expected_payload = json!({
            "aps": {
                "alert": {
                    "action-loc-key": "PLAY",
                    "body": "the body",
                    "launch-image": "foo.jpg",
                    "loc-args": ["narf", "derp"],
                    "loc-key": "PAUSE",
                    "title": "the title",
                    "title-loc-args": ["herp", "derp"],
                    "title-loc-key": "STOP"
                },
                "badge": 420,
                "category": "cat1",
                "mutable-content": 1,
                "sound": "prööt"
            }
        }).to_string();

        assert_eq!(expected_payload, payload);
    }

    #[test]
    fn test_plain_notification_with_custom_data() {
        #[derive(Serialize, Debug)]
        struct SubData {
            nothing: &'static str,
        }

        #[derive(Serialize, Debug)]
        struct TestData {
            key_str: &'static str,
            key_num: u32,
            key_bool: bool,
            key_struct: SubData,
        }

        let test_data = TestData {
            key_str: "foo",
            key_num: 42,
            key_bool: false,
            key_struct: SubData { nothing: "here" },
        };

        let mut payload = LocalizedNotificationBuilder::new("the title", "the body")
            .build("device-token", Default::default());

        payload.add_custom_data("custom", &test_data).unwrap();

        let expected_payload = json!({
            "custom": {
                "key_str": "foo",
                "key_num": 42,
                "key_bool": false,
                "key_struct": {
                    "nothing": "here"
                }
            },
            "aps": {
                "alert": {
                    "title": "the title",
                    "body": "the body",
                },
                "mutable-content": 0
            },
        }).to_string();

        assert_eq!(expected_payload, payload.to_json_string().unwrap());
    }
}