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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use std::collections::HashMap;

use serde_json::value::Value;

use action::Action;
use link::Link;
use property::Property;

/// An Entity is a URI-addressable resource that has properties and actions associated with it.
/// It may contain sub-entities and navigational links.
/// 
/// Root entities and sub-entities that are embedded representations SHOULD contain a `links` collection with at least one item contain a `rel` value of `self` and an `href` attribute with a value of the entity's URI.
/// 
/// Sub-entities that are embedded links MUST contain an `href` attribute with a value of its URI.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct Entity {
    /// A collection of action objects, represented in JSON Siren as an array such as `{ "actions": [{ ... }] }`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actions: Option<Vec<Action>>,

    /// Describes the nature of an entity's content based on the current representation.
    /// Possible values are implementation-dependent and should be documented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class: Option<Vec<String>>,

    /// A collection of related sub-entities. If a sub-entity contains an `href` value, it should be treated as an embedded link.
    /// Clients may choose to optimistically load embedded links.
    /// If no `href` value exists, the sub-entity is an embedded entity representation that contains all the characteristics of a typical entity.
    /// One difference is that a sub-entity MUST contain a `rel` attribute to describe its relationship to the parent entity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entities: Option<Vec<Box<Entity>>>,

    /// The URI of the linked sub-entity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub href: Option<String>,

    /// A collection of items that describe navigational links, distinct from entity relationships.
    /// Link items should contain a `rel` attribute to describe the relationship and an href attribute to point to the target URI.
    /// Entities should include a link `rel` to `self`.
    /// In JSON Siren, this is represented as `"links": [{ "rel": ["self"], "href": "http://api.x.io/orders/1234" }]`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,

    /// A set of key-value pairs that describe the state of an entity.
    /// In JSON Siren, this is an object such as `{ "name": "Kevin", "age": 30 }`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, Value>>,

    /// Defines the relationship of the sub-entity to its parent, per [Web Linking (RFC5988)](http://tools.ietf.org/html/rfc5988) and [Link Relations](http://www.iana.org/assignments/link-relations/link-relations.xhtml).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rel: Option<Vec<String>>,

    /// Descriptive text about the entity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

impl Entity {
    pub fn builder() -> EntityBuilder {
        EntityBuilder {
            actions: None,
            class: None,
            entities: None,
            href: None,
            links: None,
            properties: None,
            rel: None,
            title: None,
        }
    }

    /// Returns a reference to the Entity's Actions.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .actions(vec![
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items"),
    ///     ]).into();
    /// 
    /// assert_eq!(
    ///     &Some(vec![
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items").into(),
    ///     ]),
    ///     entity.actions(),
    /// );
    /// ```
    pub fn actions(&self) -> &Option<Vec<Action>> {
        &self.actions
    }

    /// Returns a reference to the Entity's classes.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .classes(vec!["item"]).into();
    /// 
    /// assert_eq!(&Some(vec!["item".to_string()]), entity.classes());
    /// ```
    pub fn classes(&self) -> &Option<Vec<String>> {
        &self.class
    }

    /// Returns a reference to the Entity's Entities.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .entities(vec![Entity::builder()]).into();
    /// 
    /// assert_eq!(&Some(vec![Box::new(Entity::builder().into())]), entity.entities());
    /// ```
    pub fn entities(&self) -> &Option<Vec<Box<Entity>>> {
        &self.entities
    }

    /// Returns a reference to the Entity's href.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .href("http://api.x.io/orders/42/items").into();
    /// 
    /// assert_eq!(&Some("http://api.x.io/orders/42/items".to_string()), entity.href());
    /// ```
    pub fn href(&self) -> &Option<String> {
        &self.href
    }

    /// Returns a reference to the Entity's Links.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .links(vec![
    ///         Link::builder(vec!["self"], "http://api.x.io/customers/pj123")
    ///     ]).into();
    /// ```
    pub fn links(&self) -> &Option<Vec<Link>> {
        &self.links
    }

    /// Returns a reference to the Entity's Properties.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .properties(vec![
    ///         Property::new("customerId", "pj123"),
    ///         Property::new("name", "Peter Joseph"),
    ///     ]).into();
    /// ```
    pub fn properties(&self) -> &Option<HashMap<String, Value>> {
        &self.properties
    }

    /// Returns a reference to the Entity's rel vector.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .rel(vec!["http://x.io/rels/customer"]).into();
    /// 
    /// assert_eq!(&Some(vec!["http://x.io/rels/customer".to_string()]), entity.rel());
    /// ```
    pub fn rel(&self) -> &Option<Vec<String>> {
        &self.rel
    }

    /// Returns a reference to the Entity's title.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .title("example").into();
    /// 
    /// assert_eq!(&Some("example".to_string()), entity.title());
    /// ```
    pub fn title(&self) -> &Option<String> {
        &self.title
    }
}

/// A builder of Entities.
#[derive(Clone, Debug, PartialEq)]
pub struct EntityBuilder {
    /// A collection of action objects, represented in JSON Siren as an array such as `{ "actions": [{ ... }] }`.
    actions: Option<Vec<Action>>,

    /// Describes the nature of an entity's content based on the current representation.
    /// Possible values are implementation-dependent and should be documented.
    class: Option<Vec<String>>,

    /// A collection of related sub-entities. If a sub-entity contains an `href` value, it should be treated as an embedded link.
    /// Clients may choose to optimistically load embedded links.
    /// If no `href` value exists, the sub-entity is an embedded entity representation that contains all the characteristics of a typical entity.
    /// One difference is that a sub-entity MUST contain a `rel` attribute to describe its relationship to the parent entity.
    entities: Option<Vec<Box<Entity>>>,

    /// The URI of the linked sub-entity.
    href: Option<String>,

    /// A collection of items that describe navigational links, distinct from entity relationships.
    /// Link items should contain a `rel` attribute to describe the relationship and an href attribute to point to the target URI.
    /// Entities should include a link `rel` to `self`.
    /// In JSON Siren, this is represented as `"links": [{ "rel": ["self"], "href": "http://api.x.io/orders/1234" }]`.
    links: Option<Vec<Link>>,

    /// A set of key-value pairs that describe the state of an entity.
    /// In JSON Siren, this is an object such as `{ "name": "Kevin", "age": 30 }`.
    properties: Option<HashMap<String, Value>>,

    /// Defines the relationship of the sub-entity to its parent, per [Web Linking (RFC5988)](http://tools.ietf.org/html/rfc5988) and [Link Relations](http://www.iana.org/assignments/link-relations/link-relations.xhtml).
    rel: Option<Vec<String>>,

    /// Descriptive text about the entity.
    title: Option<String>,
}

impl EntityBuilder {
    /// Adds and Action to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .action(
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items")
    ///     ).into();
    /// 
    /// assert_eq!(
    ///     &Some(vec![
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items").into(),
    ///     ]),
    ///     entity.actions(),
    /// );
    /// ```
    pub fn action(self, action: impl Into<Action>) -> Self {
        self.actions(vec![action])
    }

    /// Adds a list of Actions to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .actions(vec![
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items"),
    ///     ]).into();
    /// 
    /// assert_eq!(
    ///     &Some(vec![
    ///         Action::builder("add-item", "http://api.x.io/orders/42/items").into(),
    ///     ]),
    ///     entity.actions(),
    /// );
    /// ```
    pub fn actions(mut self, actions: Vec<impl Into<Action>>) -> Self {
        if let Some(ref mut s_action) = self.actions {
            for action in actions.into_iter() {
                s_action.push(action.into());
            }
        } else {
            self.actions = Some(actions.into_iter().map(|a| a.into()).collect());
        }

        self
    }

    /// Add a class to the Entity
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .class("item").into();
    /// 
    /// assert_eq!(&Some(vec!["item".to_string()]), entity.classes());
    /// ```
    pub fn class(self, class: impl Into<String>) -> Self {
        self.classes(vec![class])
    }

    /// Add a vector of classes to the Entity
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .classes(vec!["item"]).into();
    /// 
    /// assert_eq!(&Some(vec!["item".to_string()]), entity.classes());
    /// ```
    pub fn classes(mut self, classes: Vec<impl Into<String>>) -> Self {
        if let Some(ref mut s_class) = self.class {
            for class in classes.into_iter() {
                s_class.push(class.into());
            }
        } else {
            self.class = Some(classes.into_iter().map(|c| c.into()).collect());
        }

        self
    }

    /// Add an Entity to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .entity(Entity::builder()).into();
    /// 
    /// assert_eq!(&Some(vec![Box::new(Entity::builder().into())]), entity.entities());
    /// ```
    pub fn entity(self, entity: impl Into<Entity>) -> Self {
        self.entities(vec![entity])
    }

    /// Add a vector of Entities to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .entities(vec![Entity::builder()]).into();
    /// 
    /// assert_eq!(&Some(vec![Box::new(Entity::builder().into())]), entity.entities());
    /// ```
    pub fn entities(mut self, entities: Vec<impl Into<Entity>>) -> Self {
        if let Some(ref mut s_entities) = self.entities {
            for entity in entities.into_iter() {
                s_entities.push(Box::new(entity.into()));
            }
        } else {
            self.entities = Some(entities.into_iter().map(|e| Box::new(e.into())).collect());
        }

        self
    }

    /// Set the Entity's href.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .href("http://api.x.io/orders/42/items").into();
    /// 
    /// assert_eq!(&Some("http://api.x.io/orders/42/items".to_string()), entity.href());
    /// ```
    pub fn href(mut self, href: impl Into<String>) -> Self {
        self.href = Some(href.into());

        self
    }

    /// Add a Link to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .link(Link::builder(vec!["self"], "http://api.x.io/customers/pj123"))
    ///     .into();
    /// 
    /// assert_eq!(
    ///     &Some(vec![
    ///         Link::builder(vec!["self"], "http://api.x.io/customers/pj123").into()
    ///     ]),
    ///     entity.links(),
    /// );
    /// ```
    pub fn link(self, link: impl Into<Link>) -> Self {
        self.links(vec![link])
    }

    /// Add a vector of Links to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .links(vec![
    ///         Link::builder(vec!["self"], "http://api.x.io/customers/pj123")
    ///     ]).into();
    /// 
    /// assert_eq!(
    ///     &Some(vec![
    ///         Link::builder(vec!["self"], "http://api.x.io/customers/pj123").into()
    ///     ]),
    ///     entity.links(),
    /// );
    /// ```
    pub fn links(mut self, links: Vec<impl Into<Link>>) -> Self {
        if let Some(ref mut s_links) = self.links {
            for link in links.into_iter() {
                s_links.push(link.into());
            }
        } else {
            self.links = Some(links.into_iter().map(|l| l.into()).collect());
        }

        self
    }

    /// Add a Property to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .property("customerId", "pj123")
    ///     .property("name", "Peter Joseph")
    ///     .into();
    /// ```
    pub fn property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        if let Some(ref mut s_properties) = self.properties {
            s_properties.insert(key.into(), value.into());
        } else {
            let mut s_properties = HashMap::new();

            s_properties.insert(key.into(), value.into());

            self.properties = Some(s_properties);
        }

        self
    }

    /// Add a vector of Properties to the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .properties(vec![
    ///         Property::new("customerId", "pj123"),
    ///         Property::new("name", "Peter Joseph"),
    ///     ]).into();
    /// ```
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .properties(vec![
    ///         ("customerId", "pj123"),
    ///         ("name", "Peter Joseph"),
    ///     ]).into();
    /// ```
    pub fn properties(mut self, properties: Vec<impl Into<Property>>) -> Self {
        if let Some(ref mut s_properties) = self.properties {
            for property in properties.into_iter() {
                let (key, value) = property.into().get();
                s_properties.insert(key.into(), value.into());
            }
        } else {
            let mut s_properties = HashMap::new();

            for property in properties.into_iter() {
                let (key, value) = property.into().get();
                s_properties.insert(key.into(), value.into());
            }

            self.properties = Some(s_properties);
        }

        self
    }

    /// Add a vector of Rels for the Entity.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .rel(vec!["http://x.io/rels/customer"]).into();
    /// 
    /// assert_eq!(&Some(vec!["http://x.io/rels/customer".to_string()]), entity.rel());
    /// ```
    pub fn rel(mut self, rels: Vec<impl Into<String>>) -> Self {
        if let Some(ref mut s_rel) = self.rel {
            for rel in rels.into_iter() {
                s_rel.push(rel.into());
            }
        } else {
            self.rel = Some(rels.into_iter().map(|r| r.into()).collect());
        }

        self
    }

    /// Set the Entity's title.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// # extern crate vnd_siren;
    /// # use vnd_siren::prelude::*;
    /// let entity: Entity = Entity::builder()
    ///     .title("example").into();
    /// 
    /// assert_eq!(&Some("example".to_string()), entity.title());
    /// ```
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());

        self
    }
}

impl From<EntityBuilder> for Entity {
    fn from(builder: EntityBuilder) -> Entity {
        Entity {
            actions: builder.actions,
            class: builder.class,
            entities: builder.entities,
            href: builder.href,
            links: builder.links,
            properties: builder.properties,
            rel: builder.rel,
            title: builder.title,
        }
    }
}