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
use crate::Error;
use serde::Serialize;
use stac::Link;
use std::str::FromStr;
use url::{ParseError, Url};

/// Builds urls on a root url.
///
/// # Examples
///
/// ```
/// # use stac_api::UrlBuilder;
/// let url_builder = UrlBuilder::new("http://stac-api-rs.test/api/v1").unwrap();
/// assert_eq!(
///     url_builder.items("my-great-collection").unwrap().as_str(),
///     "http://stac-api-rs.test/api/v1/collections/my-great-collection/items"
/// );
/// ```
#[derive(Clone, Debug)]
pub struct UrlBuilder {
    root: Url,
    collections: Url,
    collections_with_slash: Url,
    conformance: Url,
    service_desc: Url,
    search: Url,
}

/// Build links to endpoints in a STAC API.
///
/// # Examples
///
/// [LinkBuilder] can be parsed from a string:
///
/// ```
/// # use stac_api::LinkBuilder;
/// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
/// ```
///
/// Note that the root will always have a trailing slash, even if you didn't provide one:
///
/// ```
/// # use stac_api::LinkBuilder;
/// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
/// assert_eq!(link_builder.root().href, "http://stac-api-rs.test/api/v1/");
/// ```
#[derive(Clone, Debug)]
pub struct LinkBuilder(UrlBuilder);

impl UrlBuilder {
    /// Creates a new url builder.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// ```
    pub fn new(url: &str) -> Result<UrlBuilder, ParseError> {
        let root: Url = if url.ends_with('/') {
            url.parse()?
        } else {
            format!("{}/", url).parse()?
        };
        Ok(UrlBuilder {
            collections: root.join("collections")?,
            collections_with_slash: root.join("collections/")?,
            conformance: root.join("conformance")?,
            service_desc: root.join("api")?,
            search: root.join("search")?,
            root,
        })
    }

    /// Returns the root url.
    ///
    /// The root url always has a trailing slash, even if the builder was
    /// created without one.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(url_builder.root().as_str(), "http://stac-api-rs.test/");
    /// ```
    pub fn root(&self) -> &Url {
        &self.root
    }

    /// Returns the collections url.
    ///
    /// This url is created when the builder is created, so it can't error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(url_builder.collections().as_str(), "http://stac-api-rs.test/collections");
    /// ```
    pub fn collections(&self) -> &Url {
        &self.collections
    }

    /// Returns a collection url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(
    ///     url_builder.collection("a-collection").unwrap().as_str(),
    ///     "http://stac-api-rs.test/collections/a-collection"
    /// );
    /// ```
    pub fn collection(&self, id: &str) -> Result<Url, ParseError> {
        self.collections_with_slash.join(id)
    }

    /// Returns an items url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(
    ///     url_builder.items("a-collection").unwrap().as_str(),
    ///     "http://stac-api-rs.test/collections/a-collection/items"
    /// );
    /// ```
    pub fn items(&self, id: &str) -> Result<Url, ParseError> {
        self.collections_with_slash.join(&format!("{}/items", id))
    }

    /// Returns the conformance url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(
    ///     url_builder.conformance().as_str(),
    ///     "http://stac-api-rs.test/conformance"
    /// );
    /// ```
    pub fn conformance(&self) -> &Url {
        &self.conformance
    }

    /// Returns the service-desc url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(
    ///     url_builder.service_desc().as_str(),
    ///     "http://stac-api-rs.test/api"
    /// );
    /// ```
    pub fn service_desc(&self) -> &Url {
        &self.service_desc
    }

    /// Returns the search url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::UrlBuilder;
    /// let url_builder = UrlBuilder::new("http://stac-api-rs.test").unwrap();
    /// assert_eq!(
    ///     url_builder.search().as_str(),
    ///     "http://stac-api-rs.test/search"
    /// );
    /// ```
    pub fn search(&self) -> &Url {
        &self.search
    }
}

impl LinkBuilder {
    /// Returns a root link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let root = link_builder.root();
    /// assert_eq!(root.rel, "root");
    /// assert_eq!(root.href, "http://stac-api-rs.test/api/v1/");
    /// ```
    pub fn root(&self) -> Link {
        Link::root(self.0.root())
    }

    /// Returns a root's self link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.root_to_self();
    /// assert_eq!(link.rel, "self");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/");
    /// ```
    pub fn root_to_self(&self) -> Link {
        Link::self_(self.0.root())
    }

    /// Returns the collections' self link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.collections_to_self();
    /// assert_eq!(link.rel, "self");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections");
    /// ```
    pub fn collections_to_self(&self) -> Link {
        Link::self_(self.0.collections())
    }

    /// Returns a service-desc link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.service_desc();
    /// assert_eq!(link.rel, "service-desc");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/api");
    /// ```
    pub fn service_desc(&self) -> Link {
        Link::new(self.0.service_desc(), "service-desc")
    }

    /// Returns a conformance link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.conformance();
    /// assert_eq!(link.rel, "conformance");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/conformance");
    /// ```
    pub fn conformance(&self) -> Link {
        Link::new(self.0.conformance(), "conformance")
    }

    /// Returns a collections link.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.collections();
    /// assert_eq!(link.rel, "data");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections");
    /// ```
    pub fn collections(&self) -> Link {
        Link::new(self.0.collections(), "data")
    }

    /// Returns an child link for a collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.root_to_collection("an-id").unwrap();
    /// assert_eq!(link.rel, "child");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections/an-id");
    /// ```
    pub fn root_to_collection(&self, id: &str) -> Result<Link, ParseError> {
        self.0.collection(id).map(Link::child)
    }

    /// Returns a parent link for a collection.
    ///
    /// This is just the root url.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.collection_to_parent();
    /// assert_eq!(link.rel, "parent");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/");
    /// ```
    pub fn collection_to_parent(&self) -> Link {
        Link::parent(self.0.root())
    }

    /// Returns a self link for a collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.collection_to_self("an-id").unwrap();
    /// assert_eq!(link.rel, "self");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections/an-id");
    /// ```
    pub fn collection_to_self(&self, id: &str) -> Result<Link, ParseError> {
        self.0.collection(id).map(Link::self_)
    }

    /// Returns a next items link for a collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.next_items("an-id", [("foo", "bar")]).unwrap();
    /// assert_eq!(link.rel, "next");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections/an-id/items?foo=bar");
    /// ```
    pub fn next_items<S>(&self, id: &str, parameters: S) -> Result<Link, Error>
    where
        S: Serialize,
    {
        self.items_with_rel(id, parameters, "next")
    }

    /// Returns a prev items link for a collection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.prev_items("an-id", [("foo", "bar")]).unwrap();
    /// assert_eq!(link.rel, "prev");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections/an-id/items?foo=bar");
    /// ```
    pub fn prev_items<S>(&self, id: &str, parameters: S) -> Result<Link, Error>
    where
        S: Serialize,
    {
        self.items_with_rel(id, parameters, "prev")
    }

    fn items_with_rel<S>(&self, id: &str, parameters: S, rel: impl ToString) -> Result<Link, Error>
    where
        S: Serialize,
    {
        self.0
            .items(id)
            .map_err(Error::from)
            .and_then(|url| {
                serde_urlencoded::to_string(parameters)
                    .map(|query| (url, query))
                    .map_err(Error::from)
            })
            .map(|(mut url, query)| {
                if !query.is_empty() {
                    url.set_query(Some(&query))
                }
                Link::new(url, rel).geojson()
            })
    }

    /// Returns a link from a collection to its items.
    ///
    /// # Examples
    ///
    /// ```
    /// # use stac_api::LinkBuilder;
    /// let link_builder: LinkBuilder = "http://stac-api-rs.test/api/v1".parse().unwrap();
    /// let link = link_builder.collection_to_items("an-id").unwrap();
    /// assert_eq!(link.rel, "items");
    /// assert_eq!(link.href, "http://stac-api-rs.test/api/v1/collections/an-id/items");
    /// ```
    pub fn collection_to_items(&self, id: &str) -> Result<Link, Error> {
        self.items_with_rel(id, (), "items")
    }
}

impl FromStr for UrlBuilder {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        UrlBuilder::new(s)
    }
}

impl FromStr for LinkBuilder {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<UrlBuilder>()
            .map(|url_builder| LinkBuilder(url_builder))
    }
}