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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/*!
 # Firebase REST API for Rust
 Please have a look at the ```Firebase``` struct to get started.
 */

extern crate knock;

extern crate url;
extern crate curl;

use knock::HTTP;
use knock::Data;

use std::str;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::thread::JoinHandle;

use url::Url;

/// A Firebase instance to manage data.
#[derive(Clone)]
pub struct Firebase {
    url: Arc<Url>,
}

// TODO: Change all instances of &str to Into<String>
// TODO: Make FB instance from Url and String.
// TODO: Make closure lives 'static or 'fb ?
impl Firebase {
    /// Creates a new Firebase instance from the url of the fb server
    /// The url should be a valid **HTTPS** url, anything else will
    /// result in an error:
    ///
    /// https://docs-examples.firebaseio.com/
    ///
    /// # Failures
    /// - If a url is not specified with the HTTPS scheme, a ```Err(ParseError::UrlIsNotHTTPS)```
    ///   will be returned.
    /// - If a url cannot be parsed into a valid url then a ```Err(ParseError::Parser(url::ParseError)```
    ///   will be returned.
    pub fn new(url: &str) -> Result<Self, ParseError> {
        let url = try!(parse(&url));
        if url.scheme() != "https" {
            return Err(ParseError::UrlIsNotHTTPS);
        }
        try!(unwrap_path(&url));

        Ok(Firebase {
            url: Arc::new(url),
        })
    }

    /// Creates a firebase reference from a borrow of a Url instance.
    /// # Failures
    /// - If a url is not specified with the HTTPS scheme, a ```Err(ParseError::UrlIsNotHTTPS)```
    ///   will be returned.
    /// - If a url cannot be parsed into a valid url then a ```Err(ParseError::Parser(url::ParseError)```
    ///   will be returned.
    pub fn from_url(url: &Url) -> Result<Self, ParseError> {
        let url = url.clone();
        try!(unwrap_path(&url));

        Ok(Firebase {
            url: Arc::new(url),
        })
    }

    /// Creates a new authenticated Firebase instance from the firebaseio url and an auth token.
    ///
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let fb = Firebase::authed("https://myfb.firebaseio.com", "deadbeefcafe");
    /// // The url shoud now be: https://myfb.firebaseio.com?auth=deadbeefcafe
    /// ```
    ///
    /// # Failures
    /// - If a url is not specified with the HTTPS scheme, a ```Err(ParseError::UrlIsNotHTTPS)```
    ///   will be returned.
    /// - If a url cannot be parsed into a valid url then a ```Err(ParseError::Parser(url::ParseError)```
    ///   will be returned.
    pub fn authed(url: &str, auth_token: &str) -> Result<Self, ParseError> {
        let mut url = try!(parse(&url));
        if url.scheme() != "https" {
            return Err(ParseError::UrlIsNotHTTPS);
        }
        try!(unwrap_path(&url));

        let opts = vec![(AUTH, auth_token)];
        url.set_query(Some(&format!("{}{}{}", AUTH.to_owned(), "=", auth_token.to_owned())[..]));
        Ok(Firebase {
            url: Arc::new(url),
        })
    }

    /// Creates a new firebase instance that extends the path of an old firebase instance.
    /// Each time a reference is created a clone of the Firebase instance if done, all
    /// Firebase instances follow this immutable style.
    ///
    /// #Examples
    /// ```
    /// # use firebase::Firebase;
    /// // Points to the root of the db ( / )
    /// let fb = Firebase::new("https://myfb.firebaseio.com").unwrap();
    /// // A new reference to /friends/yasha
    /// let yasha = fb.at("/friends/yasha").unwrap();
    /// // A new reference to /friends/yasha/messages
    /// let messages = yasha.at("messages").unwrap();
    pub fn at(&self, add_path: &str) -> Result<Self, ParseError> {
        let mut url = (*self.url).clone();

        { // Add path to original path, already checked for path.
            let mut path = url.path().to_owned();
//             Remove .json from the old path's end.
//      Todo check this      if let Some(end) = path.pop() {
//            path.push_str(end.trim_right_matches(".json").to_string());
//            }
            let add_path = add_path.trim_matches('/');
            let add_path = if !add_path.ends_with(".json") {
                Cow::Owned(add_path.to_string() + ".json")
            } else {
                Cow::Borrowed(add_path)
            };

            for component in add_path.split("/") {
                path.push_str(component);
            }
        }

        Ok(Firebase {
            url: Arc::new(url),
        })
    }

    /// Creates a FirebaseParams instance, this instance has query parameters
    /// that are associated with it and that are used in every request made.
    /// Since query parameters only affect incomming data from Firebase, you can only
    /// GET data with a FirebaseParams instance.
    ///
    /// This constructor takes in a FbOps struct to define all of its parameters,
    /// all undefined parameters can be omitted by extending the new FbOps struct
    /// by its default.
    ///
    /// # Examples
    /// ```
    /// # use firebase::*;
    /// let fb = Firebase::new("https://db.fb.com").unwrap();
    /// let query = fb.ops(&FbOps {
    ///    order_by:       Some("Hello World"),
    ///    limit_to_first: Some(5),
    ///    end_at:         Some(7),
    ///    equal_to:       Some(3),
    ///    shallow:        Some(true),
    ///    format:         Some(true),
    ///    .. FbOps::default()
    /// });
    /// ```
    pub fn ops(&self, opts: &FbOps) -> FirebaseParams {
        FirebaseParams::from_ops(&self.url, opts)
    }

    /// Returns the current URL as a string that will be used
    /// to make the REST call when talking to Firebase.
    pub fn get_url(&self) -> String {
        self.url.as_str().to_owned()
    }

    /// Gets data from Firebase.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let episode = firebase.at("/futurama/episodes/140").unwrap();
    /// let info = episode.get();
    /// ```
    pub fn get(&self) -> Result<Response, i64> {
        self.request(Method::GET, None)
    }

    /// Sets data to Firebase.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let episode = firebase.at("/futurama/episodes/140/description").unwrap();
    /// let info = episode.set("The Last Episode!");
    /// ```
    pub fn set(&self, data: HashMap<String, Data>) -> Result<Response, i64> {
        self.request(Method::PUT, Some(data))
    }

    /// Pushes data to Firebase.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let episodes = firebase.at("/futurama/episodes").unwrap();
    /// let info = episodes.push("The Lost Episode");
    /// ```
    pub fn push(&self, data: HashMap<String, Data>) -> Result<Response, i64> {
        self.request(Method::POST, Some(data))
    }

    /// Updates Firebase data.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let desc = firebase.at("/futurama/episodes/140/description").unwrap();
    /// let info = desc.update("The Penultimate Episode!");
    /// ```
    pub fn update(&self, data: HashMap<String, Data>) -> Result<Response, i64> {
        self.request(Method::PATCH, Some(data))
    }

    /// Removes Firebase data.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let episode = firebase.at("/futurama/episodes/141").unwrap();
    /// episode.remove();
    /// ```
    pub fn remove(&self) -> Result<Response, i64> {
        self.request(Method::DELETE, None)
    }

    /// Asynchronous version of the get method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let firebase = Firebase::new("https://shows.firebaseio.com").unwrap();
    /// let desc = firebase.at("/futurama/episodes/141/description").unwrap();
    /// let original = "The Lost Episode";
    /// desc.get_async(move |result| {
    ///     if result.unwrap().body != original {
    ///         println!("The description changed!");
    ///     }
    /// });
    pub fn get_async<F>(&self, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        Firebase::request_url_async(&self.url, Method::GET, HashMap::new(), callback)
    }

    /// Asynchronous version of the set method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    pub fn set_async<S, F>(&self, data: HashMap<String, Data>, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static, S: Into<String> {
        Firebase::request_url_async(&self.url, Method::PUT, data, callback)
    }

    /// Asynchronous version of the push method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    pub fn push_async<S, F>(&self, data: HashMap<String, Data>, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        Firebase::request_url_async(&self.url, Method::POST, data, callback)
    }

    /// Asynchronous version of the update method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    pub fn update_async<S, F>(&self, data: HashMap<String, Data>, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        Firebase::request_url_async(&self.url, Method::PATCH, data, callback)
    }

    /// Asynchronous version of the remove method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    /// Todo remove all the empty hashes
    pub fn remove_async<F>(&self, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        Firebase::request_url_async(&self.url, Method::DELETE, HashMap::new(), callback)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and sorts this data by the key provided.
    pub fn order_by(&self, key: &str) -> FirebaseParams {
        self.with_params(ORDER_BY, key)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and limits the number of entries returned
    /// on each request to the first ```count```. Often used with ```order_by```.
    pub fn limit_to_first(&self, count: u32) -> FirebaseParams {
        self.with_params(LIMIT_TO_FIRST, count)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and limits the number of entries returned
    /// on each request to the last ```count```. Often used with ```order_by```.
    pub fn limit_to_last(&self, count: u32) -> FirebaseParams {
        self.with_params(LIMIT_TO_LAST, count)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and only returns entries starting after
    /// the specified index. Often used with ```order_by```.
    pub fn start_at(&self, index: u32) -> FirebaseParams {
        self.with_params(START_AT, index)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and only returns entries appearing before
    /// the specified index. Often used with ```order_by```.
    pub fn end_at(&self, index: u32) -> FirebaseParams {
        self.with_params(END_AT, index)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and returns only the entry at the specified
    /// index. Often used with ```order_by```.
    pub fn equal_to(&self, index: u32) -> FirebaseParams {
        self.with_params(EQUAL_TO, index)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and only returns a shallow copy of the db
    /// in every request.
    pub fn shallow(&self, flag: bool) -> FirebaseParams {
        self.with_params(SHALLOW, flag)
    }

    /// Creates a ```FirebaseParams``` instance, a Firebase struct that only
    /// knows how to GET data, and formats the data to be exported in every
    /// request. (e.g. includes a priority field).
    pub fn format(&self) -> FirebaseParams {
        self.with_params(FORMAT, EXPORT)
    }

    #[inline]
    fn request(&self, method: Method, data: Option<HashMap<String, Data>>) -> Result<Response, i64> {
        Firebase::request_url(&self.url, method, data.unwrap())
    }

    fn request_url(url: &Url, method: Method, data: HashMap<String, Data>) -> Result<Response, i64> {
        let mut http = HTTP::new(url.as_str()).unwrap();

        let response = match method {
            Method::GET => http.get().send(),
            Method::POST => http.post().body(data).send(),
            Method::PUT => http.put().body(data).send(),
//            TODO add patch method
            Method::DELETE => http.delete().body(data).send(),
            _ => http.post().body(data).send(),
        };

        //Todo fix status codes
        let res: Response = Response { body: response.unwrap().as_str().to_owned(), code: 200i64 };
//        Ok(res);
        //Todo fix
        Err(-1)
    }

    fn request_url_async<F>(url: &Arc<Url>, method: Method, data: HashMap<String, Data>, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        // Fast, because its in an arc.
        let url = url.clone();

        thread::spawn(move || {
            callback(Firebase::request_url(&url, method, data));
        })
    }

    fn with_params<T: ToString>(&self, key: &'static str, value: T) -> FirebaseParams {
        FirebaseParams::new(&self.url, key, value)
    }
}

/// The FirebaseParams struct is a Firebase reference with attatched
/// query parameters that allow you to sort, limit, and format the data
/// received from Firebase.
///
/// It has been made into its own struct because the Firebase API specifies
/// that you can only GET data with query parameters. And so taking advantage of
/// type systems, this struct can only GET data.
///
/// You can add any number of parameters to this struct by chaining calls together:
///
/// ```
/// # use firebase::*;
/// let episodes = Firebase::new("https://futurama.firebaseio.com/episodes/").unwrap();
/// let alphabetic = episodes.order_by("\"title\"").limit_to_first(5);
/// let first5 = alphabetic.get();
/// ```
///
/// Setting the same parameter overwrites the previous parameter:
///
/// ```
/// # use firebase::*;
/// let episodes = Firebase::new("https://arrdev.firebaseio.com/episodes/").unwrap();
/// // This will create a request that gets entries starting at the 0th index.
/// let skip10 = episodes.start_at(10).start_at(0);
/// ```
#[derive(Clone)]
pub struct FirebaseParams {
    url: Arc<Url>,
    params: HashMap<&'static str, String>,
}

impl FirebaseParams {
    /// Gets data from Firebase.
    /// # Examples
    /// ```
    /// # use firebase::Firebase;
    /// let episodes = Firebase::new("https://futurama.firebaseio.com/episodes/").unwrap();
    /// let alphabetic = episodes.order_by("\"title\"").limit_to_first(5);
    /// let first5 = alphabetic.get();
    /// ```
    pub fn get(&self) -> Result<Response, i64> {
        //Todo remove empty hash
        Firebase::request_url(&self.url, Method::GET, HashMap::new())
    }

    /// Asynchronous version of the get method, takes a callback
    /// and returns a handle to the thread making the request to Firebase.
    pub fn get_async<F>(&self, callback: F) -> JoinHandle<()>
        where F: Fn(Result<Response, i64>) + Send + 'static {
        //Todo remove empty hash
        Firebase::request_url_async(&self.url, Method::GET, HashMap::new(), callback)
    }

    /// Returns the current URL as a string that will be used
    /// to make the REST call when talking to Firebase.
    pub fn get_url(&self) -> String {
        self.url.as_str().to_owned()
    }

    // TODO: Wrap in quotes if not already. Or always wrap in quotes.
    /// Modifies the current ```FirebaseParams``` instance
    /// and sorts this data by the key provided.
    pub fn order_by(self, key: &str) -> Self {
        self.add_param(ORDER_BY, key)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and limits the number of entries returned
    /// on each request to the first ```count```. Often used with ```order_by```.
    pub fn limit_to_first(self, count: u32) -> Self {
        self.add_param(LIMIT_TO_FIRST, count)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and limits the number of entries returned
    /// on each request to the last ```count```. Often used with ```order_by```.
    pub fn limit_to_last(self, count: u32) -> Self {
        self.add_param(LIMIT_TO_LAST, count)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and only returns entries starting after
    /// the specified index. Often used with ```order_by```.
    pub fn start_at(self, index: u32) -> Self {
        self.add_param(START_AT, index)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and only returns entries appearing before
    /// the specified index. Often used with ```order_by```.
    pub fn end_at(self, index: u32) -> Self {
        self.add_param(END_AT, index)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and returns only the entry at the specified
    /// index. Often used with ```order_by```.
    pub fn equal_to(self, value: u32) -> Self {
        self.add_param(EQUAL_TO, value)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and only returns a shallow copy of the db
    /// in every request.
    pub fn shallow(self, flag: bool) -> Self {
        self.add_param(SHALLOW, flag)
    }

    /// Modifies the current ```FirebaseParams``` instance
    /// and formats the data to be exported in every
    /// request. (e.g. includes a priority field)
    pub fn format(self) -> Self {
        self.add_param(FORMAT, EXPORT)
    }

    fn add_param<T: ToString>(mut self, key: &'static str, value: T) -> Self {
        let value = value.to_string();
        self.params.insert(key, value);
        self.set_params();
        self
    }

    fn set_params(&mut self) {
        // Only clones the url when edited. This is CoW
        // Many threads can run requests without ever cloning the url.
        let mut url = (*self.url).clone();
        //Todo check this one
//        url.map(|(&k, v)| (k, v as &str));
        self.url = Arc::new(url);
    }

    fn get_auth(url: &Url) -> HashMap<&'static str, String> {
        let mut pair: HashMap<&'static str, String> = HashMap::new();
        println!("get auth");
        for (ref k, ref v) in url.query_pairs().enumerate().into_iter() {
//            if k == AUTH {
//                pair.insert(AUTH, v.to_owned());
//            }
            println!("{:?}", v);
        }
        pair
    }

    fn new<T: ToString>(url: &Url, key: &'static str, value: T) -> Self {
        let me = FirebaseParams {
            url: Arc::new(url.clone()),
            params: FirebaseParams::get_auth(&url),
        };
        me.add_param(key, value)
    }

    fn from_ops(url: &Url, opts: &FbOps) -> Self {
        let mut me = FirebaseParams {
            url: Arc::new(url.clone()),
            params: FirebaseParams::get_auth(&url),
        };
        if let Some(order) = opts.order_by {
            me.params.insert(ORDER_BY, order.to_string());
        }
        if let Some(first) = opts.limit_to_first {
            me.params.insert(LIMIT_TO_FIRST, first.to_string());
        }
        if let Some(last) = opts.limit_to_last {
            me.params.insert(LIMIT_TO_LAST, last.to_string());
        }
        if let Some(start) = opts.start_at {
            me.params.insert(START_AT, start.to_string());
        }
        if let Some(end) = opts.end_at {
            me.params.insert(END_AT, end.to_string());
        }
        if let Some(equal) = opts.equal_to {
            me.params.insert(EQUAL_TO, equal.to_string());
        }
        if let Some(shallow) = opts.shallow {
            me.params.insert(SHALLOW, shallow.to_string());
        }
        if let Some(format) = opts.format {
            if format {
                me.params.insert(FORMAT, EXPORT.to_string());
            }
        }
        // Copy all of the params into the url.
        me.set_params();
        me
    }
}

enum Method {
    GET,
    POST,
    PUT,
    PATCH,
    DELETE,
}

const ORDER_BY: &'static str = "orderBy";
const LIMIT_TO_FIRST: &'static str = "limitToFirst";
const LIMIT_TO_LAST: &'static str = "limitToLast";
const START_AT: &'static str = "startAt";
const END_AT: &'static str = "endAt";
const EQUAL_TO: &'static str = "equalTo";
const SHALLOW: &'static str = "shallow";
const FORMAT: &'static str = "format";
const EXPORT: &'static str = "export";
const AUTH: &'static str = "auth";

#[derive(Debug)]
pub struct FbOps<'l> {
    pub order_by: Option<&'l str>,
    pub limit_to_first: Option<u32>,
    pub limit_to_last: Option<u32>,
    pub start_at: Option<u32>,
    pub end_at: Option<u32>,
    pub equal_to: Option<u32>,
    pub shallow: Option<bool>,
    pub format: Option<bool>,
}

impl<'l> Default for FbOps<'l> {
    fn default() -> Self {
        FbOps {
            order_by: None,
            limit_to_first: None,
            limit_to_last: None,
            start_at: None,
            end_at: None,
            equal_to: None,
            shallow: None,
            format: None,
        }
    }
}


#[derive(Debug)]
pub enum ParseError {
    UrlHasNoPath,
    UrlIsNotHTTPS,
    Parser(url::ParseError),
}

#[derive(Debug)]
pub struct Response {
    pub body: String,
    pub code: i64,
}

impl Response {
    /// Returns true if the status code is 200
    pub fn is_success(&self) -> bool {
        *(&self.code) == 200
    }

    /// Returns the body as a string Json enum.
    pub fn body(&self) -> &String {
        (&self.body)
    }
}

fn parse(url: &str) -> Result<Url, ParseError> {
    match Url::parse(&url) {
        Ok(u) => Ok(u),
        Err(e) => Err(ParseError::Parser(e)),
    }
}

fn unwrap_path(url: &Url) -> Result<[String; 1], ParseError> {
//    match url.path().to_owned() {
//        None => return Err(Box::new(ParseError::UrlHasNoPath)),
//        Some(p) => return Ok(Box::new(p)),
//    }
    Ok([url.path().to_owned()])
}

// This code will happen when Trait Specialization becomes available
// in rust.
// pub trait ToJsonStr {
//     fn to_json_str(&self) -> Result<Cow<str>, /* TODO */ Box<Error>>;
// }
//
// impl<'l> ToJsonStr for &'l str {
//     fn to_json_str(&self) -> Result<Cow<str>, /* TODO */ Box<Error>> {
//         Ok(Cow::Borrowed(self))
//     }
// }
//
// impl<S> ToJsonStr for S where S: Encodable {
//     fn to_json_str(&self) -> Result<Cow<str>, /* TODO */ Box<Error>> {
//         match json::encode(self) {
//             Ok(encoded) => Ok(Cow::Owned(encoded)),
//             Err(e)      => Err(Box::new(e)),
//         }
//     }
// }