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
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
/*Copyright 2016-2018 Jesse C. Grillo

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

#![doc(html_root_url = "https://jgrillo.github.io/forecast-rs/")]

//! This module exposes an SDK for interacting with the [Dark Sky
//! API](https://darksky.net/dev/docs/).
//!
//! # Overview
//!
//! The `ApiClient` is the main entrypoint. It exposes two methods for
//! sending HTTP requests to the Dark Sky API:
//!
//!   1. `ApiClient::get_forecast(request: ForecastRequest)` makes an
//!   HTTP request against the API and returns a deserialized response
//!   containing a weather forecast given the current weather
//!   conditions.
//!
//!   2. `ApiClient::get_time_machine(request: TimeMachineRequest)`
//!   makes a request against the API and returns a deserialized
//!   response containing weather data corresponding to the `time`
//!   parameter in the `TimeMachineRequest`.
//!
//! For your convenience, there are two builder objects
//! `ForecastRequestBuilder` and `TimeMachineRequestBuilder` which you
//! can use to construct `ForecastRequest` and `TimeMachineRequest`
//! instances.
//!
//! # Examples
//!
//! The following example builds a `ForecastRequest` and a
//! `TimeMachineRequest` and executes them against the API:
//!
//! ```
//! extern crate reqwest;
//! extern crate forecast;
//!
//! use reqwest::Client;
//!
//! use forecast::{ApiResponse, ApiClient, ForecastRequestBuilder,
//!                TimeMachineRequestBuilder, ExcludeBlock, ExtendBy,
//!                Lang, Units};
//!
//! const LAT: f64 = 6.66;
//! const LONG: f64 = 66.6;
//! const TIME: u64 = 666;
//!
//! fn main() {
//!     let api_key = "my_dark_sky_api_key"; // please don't actually hardcode your API key!
//!
//!     let reqwest_client = Client::new();
//!     let api_client = ApiClient::new(&reqwest_client);
//!
//!     let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];
//!
//!     let forecast_request = ForecastRequestBuilder::new(api_key, LAT, LONG)
//!         .exclude_block(ExcludeBlock::Hourly)
//!         .exclude_blocks(&mut blocks)
//!         .extend(ExtendBy::Hourly)
//!         .lang(Lang::Arabic)
//!         .units(Units::Imperial)
//!         .build();
//!
//!     let time_machine_request = TimeMachineRequestBuilder::new(api_key, LAT, LONG, TIME)
//!         .exclude_block(ExcludeBlock::Hourly)
//!         .exclude_blocks(&mut blocks)
//!         .lang(Lang::Arabic)
//!         .units(Units::Imperial)
//!         .build();
//!
//!     // let forecast_response = api_client.get_forecast(forecast_request).unwrap();
//!     // let time_machine_response = api_client.get_time_machine(time_machine_request).unwrap();
//! }
//! ```

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

extern crate itertools;

extern crate reqwest;

use std::vec::Vec;
use std::option::Option;

use itertools::join;

use reqwest::{Url, Result as ApiResult, Client, Response};
use reqwest::header::{Encoding, AcceptEncoding, qitem};

// constants

static FORECAST_URL: &'static str = "https://api.darksky.net/forecast";
static EXCLUDE: &'static str = "exclude";
static EXTEND: &'static str = "extend";
static LANG: &'static str = "lang";
static UNITS: &'static str = "units";

// api objects

/// The ApiClient is a thin wrapper around a `reqwest::Client` which
/// sends requests to the Forecast and Time Machine APIs.
#[derive(Debug)]
pub struct ApiClient<'a> {
    client: &'a Client
}

impl<'a> ApiClient<'a> {
    /// Construct a new ApiClient.
    pub fn new(client: &'a Client) -> ApiClient<'a> {
        ApiClient { client }
    }

    /// Send a [Forecast API](https://darksky.net/dev/docs/forecast)
    /// request, returns the corresponding Response.
    ///
    /// # Errors
    ///
    /// This function is a thin wrapper around
    /// `reqwest::Client.get(..)`, so it will return an error under the
    /// same conditions in which reqwest would.
    pub fn get_forecast(self, request: ForecastRequest) -> ApiResult<Response> {
        self.client.get(request.url)
            .header(AcceptEncoding(vec![qitem(Encoding::Gzip)]))
            .send()
    }

    /// Send a [Time Machine
    /// API](https://darksky.net/dev/docs/time-machine) request,
    /// returns the corresponding Response.
    ///
    /// # Errors
    ///
    /// This function is a thin wrapper around
    /// `reqwest::Client.get(..)`, so it will return an error under the
    /// same conditions in which reqwest would.
    pub fn get_time_machine(self, request: TimeMachineRequest) -> ApiResult<Response> {
        self.client.get(request.url)
            .header(AcceptEncoding(vec![qitem(Encoding::Gzip)]))
            .send()
    }
}

// request model objects and their builders

/// Model object representing a request to the Forecast API.
#[derive(Debug, Clone, PartialEq)]
pub struct ForecastRequest<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    url: Url,
    exclude: Vec<ExcludeBlock>,
    extend: Option<ExtendBy>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> ForecastRequest<'a> {
    pub fn new(
        api_key: &'a str,
        latitude: f64,
        longitude: f64,
        url: Url,
        exclude: Vec<ExcludeBlock>,
        extend: Option<ExtendBy>,
        lang: Option<Lang>,
        units: Option<Units>
    ) -> ForecastRequest<'a> {
        ForecastRequest {
            api_key,
            latitude,
            longitude,
            url,
            exclude,
            extend,
            lang,
            units
        }
    }
}

/// Builder object used to construct a ForecastRequest.
#[derive(Debug, Clone, PartialEq)]
pub struct ForecastRequestBuilder<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    exclude: Vec<ExcludeBlock>,
    extend: Option<ExtendBy>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> ForecastRequestBuilder<'a> {
    /// A Forecast API request is constructed with required params
    /// `api_key`, `latitude`, and `longitude`.
    pub fn new(api_key: &'a str, latitude: f64, longitude: f64) -> ForecastRequestBuilder {
        ForecastRequestBuilder {
            api_key,
            latitude,
            longitude,
            exclude: Vec::new(),
            extend: None,
            lang: None,
            units: None
        }
    }

    /// Add a DataBlock to exclude from the response.
    pub fn exclude_block(mut self, exclude_block: ExcludeBlock) -> ForecastRequestBuilder<'a> {
        self.exclude.push(exclude_block);
        self
    }

    /// Add multiple DataBlocks to exclude from the response.
    pub fn exclude_blocks(mut self, exclude_blocks: &mut Vec<ExcludeBlock>)
        -> ForecastRequestBuilder<'a> {
        self.exclude.append(exclude_blocks);
        self
    }

    /// Extend the time window of the response data from 48 hours to
    /// 168 hours.
    pub fn extend(mut self, extend: ExtendBy) -> ForecastRequestBuilder<'a> {
        self.extend = Some(extend);
        self
    }

    /// Set the language for messages in the response data.
    pub fn lang(mut self, lang: Lang) -> ForecastRequestBuilder<'a> {
        self.lang = Some(lang);
        self
    }

    /// Set the measurement units for response data.
    pub fn units(mut self, units: Units) -> ForecastRequestBuilder<'a> {
        self.units = Some(units);
        self
    }

    /// Finalize the request.
    pub fn build(self) -> ForecastRequest<'a> {
        ForecastRequest::new(
            self.api_key,
            self.latitude,
            self.longitude,
            self.build_url(),
            self.exclude,
            self.extend,
            self.lang,
            self.units
        )
    }

    fn build_url(&self) -> Url {
        let url_string = format!(
            "{base}/{key}/{lat:.16},{long:.16}",
            base = FORECAST_URL,
            key = &self.api_key,
            lat = &self.latitude,
            long = &self.longitude
        );

        let mut url = Url::parse(&url_string).unwrap();

        {
            let mut query_pairs = url.query_pairs_mut();

            if !&self.exclude.is_empty() {
                let excludes = join(
                    &self.exclude
                        .iter()
                        .map(|e| {
                            let json = serde_json::to_string(e).unwrap();
                            json.trim_matches('"').to_string()
                        })
                        .collect::<Vec<String>>(),
                    ","
                );

                query_pairs.append_pair(EXCLUDE, &excludes);
            }

            if let &Some(ref extend) = &self.extend {
                query_pairs.append_pair(
                    EXTEND,
                    serde_json::to_string(&extend).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref lang) = &self.lang {
                query_pairs.append_pair(
                    LANG,
                    serde_json::to_string(&lang).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref units) = &self.units {
                query_pairs.append_pair(
                    UNITS,
                    serde_json::to_string(&units).unwrap().trim_matches('"')
                );
            }
        };

        url
    }
}

/// Model object representing a request to the Time Machine API.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeMachineRequest<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    time: u64,
    url: Url,
    exclude: Vec<ExcludeBlock>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> TimeMachineRequest<'a> {
    pub fn new(
        api_key: &'a str,
        latitude: f64,
        longitude: f64,
        time: u64,
        url: Url,
        exclude: Vec<ExcludeBlock>,
        lang: Option<Lang>,
        units: Option<Units>
    ) -> TimeMachineRequest<'a> {
        TimeMachineRequest {
            api_key,
            latitude,
            longitude,
            time,
            url,
            exclude,
            lang,
            units
        }
    }
}

/// Builder object used to construct a TimeMachineRequest.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeMachineRequestBuilder<'a> {
    api_key: &'a str,
    latitude: f64,
    longitude: f64,
    time: u64,
    exclude: Vec<ExcludeBlock>,
    lang: Option<Lang>,
    units: Option<Units>
}

impl<'a> TimeMachineRequestBuilder<'a> {
    /// A Time Machine API request is constructed with required params
    /// `api_key`, `latitude`, `longitude`, and `time`.
    pub fn new(
        api_key: &'a str,
        latitude: f64,
        longitude: f64,
        time: u64
    ) -> TimeMachineRequestBuilder {
        TimeMachineRequestBuilder {
            api_key,
            latitude,
            longitude,
            time,
            exclude: Vec::new(),
            lang: None,
            units: None
        }
    }

    /// Add a DataBlock to exclude from the response.
    pub fn exclude_block(mut self, exclude_block: ExcludeBlock) -> TimeMachineRequestBuilder<'a> {
        self.exclude.push(exclude_block);
        self
    }

    /// Add multiple DataBlocks to exclude from the response.
    pub fn exclude_blocks(
        mut self,
        exclude_blocks: &mut Vec<ExcludeBlock>
    ) -> TimeMachineRequestBuilder<'a> {
        self.exclude.append(exclude_blocks);
        self
    }

    /// Set the language for messages in the response data.
    pub fn lang(mut self, lang: Lang) -> TimeMachineRequestBuilder<'a> {
        self.lang = Some(lang);
        self
    }

    /// Set the measurement units for response data.
    pub fn units(mut self, units: Units) -> TimeMachineRequestBuilder<'a> {
        self.units = Some(units);
        self
    }

    /// Finalize the request.
    pub fn build(self) -> TimeMachineRequest<'a> {
        TimeMachineRequest::new(
            self.api_key,
            self.latitude,
            self.longitude,
            self.time,
            self.build_url(),
            self.exclude,
            self.lang,
            self.units
        )
    }

    fn build_url(&self) -> Url {
        let url_string = format!(
            "{base}/{key}/{lat:.16},{long:.16},{time}",
            base = FORECAST_URL,
            key = self.api_key,
            lat = self.latitude,
            long = self.longitude,
            time = self.time
        );

        let mut url = Url::parse(&url_string).unwrap();

        {
            let mut query_pairs = url.query_pairs_mut();

            if !self.exclude.is_empty() {
                let excludes = join(
                    &self.exclude
                        .iter()
                        .map(|e| {
                            let json = serde_json::to_string(e).unwrap();
                            json.trim_matches('"').to_string()
                        })
                        .collect::<Vec<String>>(),
                    ",",
                );

                query_pairs.append_pair(EXCLUDE, &excludes);
            }

            if let &Some(ref lang) = &self.lang {
                query_pairs.append_pair(
                    LANG,
                    serde_json::to_string(&lang).unwrap().trim_matches('"')
                );
            }

            if let &Some(ref units) = &self.units {
                query_pairs.append_pair(
                    UNITS,
                    serde_json::to_string(&units).unwrap().trim_matches('"')
                );
            }
        }

        url
    }
}

// data model objects

/// Model object representing an icon for display.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum Icon {
    #[serde(rename = "clear-day")]
    ClearDay,

    #[serde(rename = "clear-night")]
    ClearNight,

    #[serde(rename = "rain")]
    Rain,

    #[serde(rename = "snow")]
    Snow,

    #[serde(rename = "sleet")]
    Sleet,

    #[serde(rename = "wind")]
    Wind,

    #[serde(rename = "fog")]
    Fog,

    #[serde(rename = "cloudy")]
    Cloudy,

    #[serde(rename = "partly-cloudy-day")]
    PartlyCloudyDay,

    #[serde(rename = "partly-cloudy-night")]
    PartlyCloudyNight,

    #[serde(rename = "hail")]
    Hail,

    #[serde(rename = "thunderstorm")]
    Thunderstorm,

    #[serde(rename = "tornado")]
    Tornado
}

/// Model object representing the kind of precipitation occurring at a particular
/// time.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum PrecipType {
    #[serde(rename = "rain")]
    Rain,

    #[serde(rename = "snow")]
    Snow,

    #[serde(rename = "sleet")]
    Sleet
}

/// Model object representing a DataBlock to exclude from the response.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum ExcludeBlock {
    #[serde(rename = "currently")]
    Currently,

    #[serde(rename = "minutely")]
    Minutely,

    #[serde(rename = "hourly")]
    Hourly,

    #[serde(rename = "daily")]
    Daily,

    #[serde(rename = "alerts")]
    Alerts,

    #[serde(rename = "flags")]
    Flags
}

/// When present in a request, this feature causes response data to be reported
/// for 168 hours into the future instead of 48 hours.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum ExtendBy {
    #[serde(rename = "hourly")]
    Hourly
}

/// Model object representing language.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum Lang {
    #[serde(rename = "ar")]
    Arabic,

    #[serde(rename = "az")]
    Azerbaijani,

    #[serde(rename = "be")]
    Belarusian,

    #[serde(rename = "bg")]
    Bulgarian,

    #[serde(rename = "bs")]
    Bosnian,

    #[serde(rename = "ca")]
    Catalan,

    #[serde(rename = "cz")]
    Czech,

    #[serde(rename = "da")]
    Danish,

    #[serde(rename = "de")]
    German,

    #[serde(rename = "el")]
    Greek,

    #[serde(rename = "en")]
    English,

    #[serde(rename = "es")]
    Spanish,

    #[serde(rename = "et")]
    Estonian,

    #[serde(rename = "fi")]
    Finnish,

    #[serde(rename = "fr")]
    French,

    #[serde(rename = "hr")]
    Croatian,

    #[serde(rename = "hu")]
    Hungarian,

    #[serde(rename = "id")]
    Indonesian,

    #[serde(rename = "is")]
    Icelandic,

    #[serde(rename = "it")]
    Italian,

    #[serde(rename = "ja")]
    Japanese,

    #[serde(rename = "ka")]
    Georgian,

    #[serde(rename = "kw")]
    Cornish,

    #[serde(rename = "nb")]
    NorwegianBokmal,

    #[serde(rename = "nl")]
    Dutch,

    #[serde(rename = "pl")]
    Polish,

    #[serde(rename = "pt")]
    Portuguese,

    #[serde(rename = "ro")]
    Romanian,

    #[serde(rename = "ru")]
    Russian,

    #[serde(rename = "sk")]
    Slovak,

    #[serde(rename = "sl")]
    Slovenian,

    #[serde(rename = "sr")]
    Serbian,

    #[serde(rename = "sv")]
    Swedish,

    #[serde(rename = "tet")]
    Tetum,

    #[serde(rename = "tr")]
    Turkish,

    #[serde(rename = "uk")]
    Ukranian,

    #[serde(rename = "x-pig-latin")]
    IgpayAtinlay,

    #[serde(rename = "zh")]
    SimplifiedChinese,

    #[serde(rename = "zh-tw")]
    TraditionalChinese
}

/// Model object representing measurement units.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum Units {
    #[serde(rename = "auto")]
    Auto,

    #[serde(rename = "ca")]
    CA,

    #[serde(rename = "uk2")]
    UK,

    #[serde(rename = "us")]
    Imperial,

    #[serde(rename = "si")]
    SI
}

/// Model object representing an `Alert`s severity.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum Severity {
    #[serde(rename = "advisory")]
    Advisory,

    #[serde(rename = "watch")]
    Watch,

    #[serde(rename = "warning")]
    Warning
}

/// Model object containing various properties, each representing the average
/// (unless otherwise specified) of a particular weather phenomenon occurring
/// during a period of time.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct DataPoint {
    #[serde(rename = "apparentTemperature")]
    pub apparent_temperature: Option<f64>,

    #[serde(rename = "apparentTemperatureHigh")]
    pub apparent_temperature_high: Option<f64>,

    #[serde(rename = "apparentTemperatureHighTime")]
    pub apparent_temperature_high_time: Option<u64>,

    #[serde(rename = "apparentTemperatureLow")]
    pub apparent_temperature_low: Option<f64>,

    #[serde(rename = "apparentTemperatureLowTime")]
    pub apparent_temperature_low_time: Option<u64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "apparentTemperatureMax")]
    pub apparent_temperature_max: Option<f64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "apparentTemperatureMaxTime")]
    pub apparent_temperature_max_time: Option<u64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "apparentTemperatureMin")]
    pub apparent_temperature_min: Option<f64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "apparentTemperatureMinTime")]
    pub apparent_temperature_min_time: Option<u64>,

    #[serde(rename = "cloudCover")]
    pub cloud_cover: Option<f64>,

    #[serde(rename = "dewPoint")]
    pub dew_point: Option<f64>,

    pub humidity: Option<f64>,

    pub icon: Option<Icon>,

    #[serde(rename = "moonPhase")]
    pub moon_phase: Option<f64>,

    #[serde(rename = "nearestStormBearing")]
    pub nearest_storm_bearing: Option<f64>,

    #[serde(rename = "nearestStormDistance")]
    pub nearest_storm_distance: Option<f64>,

    pub ozone: Option<f64>,

    #[serde(rename = "precipAccumulation")]
    pub precip_accumulation: Option<f64>,

    #[serde(rename = "precipIntensity")]
    pub precip_intensity: Option<f64>,

    #[serde(rename = "precipIntensityMax")]
    pub precip_intensity_max: Option<f64>,

    #[serde(rename = "precipIntensityMaxTime")]
    pub precip_intensity_max_time: Option<u64>,

    #[serde(rename = "precipProbability")]
    pub precip_probability: Option<f64>,

    #[serde(rename = "precipType")]
    pub precip_type: Option<PrecipType>,

    pub pressure: Option<f64>,

    pub summary: Option<String>,

    #[serde(rename = "sunriseTime")]
    pub sunrise_time: Option<u64>,

    #[serde(rename = "sunsetTime")]
    pub sunset_time: Option<u64>,

    pub temperature: Option<f64>,

    #[serde(rename = "temperatureHigh")]
    pub temperature_high: Option<f64>,

    #[serde(rename = "temperatureHighTime")]
    pub temperature_high_time: Option<u64>,

    #[serde(rename = "temperatureLow")]
    pub temperature_low: Option<f64>,

    #[serde(rename = "temperatureLowTime")]
    pub temperature_low_time: Option<u64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "temperatureMax")]
    pub temperature_max: Option<f64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "temperatureMaxTime")]
    pub temperature_max_time: Option<u64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "temperatureMin")]
    pub temperature_min: Option<f64>,

    #[deprecated(since = "1.0.0")]
    #[serde(rename = "temperatureMinTime")]
    pub temperature_min_time: Option<u64>,

    pub time: u64,

    #[serde(rename = "uvIndex")]
    pub uv_index: Option<f64>,

    #[serde(rename = "uvIndexTime")]
    pub uv_index_time: Option<u64>,

    pub visibility: Option<f64>,

    #[serde(rename = "windBearing")]
    pub wind_bearing: Option<f64>,

    #[serde(rename = "windGust")]
    pub wind_gust: Option<f64>,

    #[serde(rename = "windGustTime")]
    pub wind_gust_time: Option<u64>,

    #[serde(rename = "windSpeed")]
    pub wind_speed: Option<f64>
}

/// Model object representing the various weather phenomena occurring over a
/// period of time.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct DataBlock {
    pub data: Vec<DataPoint>,

    pub summary: Option<String>,

    pub icon: Option<Icon>
}

/// Model object representing a severe weather warning issued by a government
/// authority for the requested location.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct Alert {
    pub description: String,

    pub expires: u64,

    pub regions: Vec<String>,

    pub severity: Severity,

    pub time: u64,

    pub title: String,

    pub uri: String
}

/// Model object representing a flag which contains miscellaneous metadata about
/// a request.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct Flags {
    #[serde(rename = "darksky-unavailable")]
    pub darksky_unavailable: Option<String>,

    pub sources: Vec<String>,

    pub units: Units
}

/// Model object representing a Forecast or Time Machine API response.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct ApiResponse {
    pub latitude: f64,

    pub longitude: f64,

    pub timezone: String,

    #[deprecated(since = "1.0.0")]
    pub offset: i64,

    pub currently: Option<DataPoint>,

    pub minutely: Option<DataBlock>,

    pub hourly: Option<DataBlock>,

    pub daily: Option<DataBlock>,

    pub alerts: Option<Vec<Alert>>,

    pub flags: Option<Flags>
}

// unit tests

#[cfg(test)]
mod tests {
    use super::{ForecastRequestBuilder, ForecastRequest, TimeMachineRequestBuilder,
                TimeMachineRequest, ExcludeBlock, Units, Lang, ExtendBy, FORECAST_URL, EXCLUDE,
                EXTEND, LANG, UNITS};

    use reqwest::Url;

    use std::vec::Vec;

    // constants

    const LAT: f64 = 6.66;
    const LONG: f64 = 66.6;
    const TIME: u64 = 666;

    static API_KEY: &'static str = "some_api_key";

    // tests for request models and their builders

    #[test]
    fn test_forecast_request_builder_defaults() {
        let request = ForecastRequestBuilder::new(API_KEY, LAT, LONG).build();

        let expected_url = Url::parse(&format!(
            "{base}/{key}/{lat:.16},{long:.16}?",
            base = FORECAST_URL,
            key = API_KEY,
            lat = LAT,
            long = LONG
        )).unwrap();

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            Vec::new(),
            None,
            None,
            None
        );

        assert_eq!(expected.api_key, request.api_key);
        assert_eq!(expected.latitude, request.latitude);
        assert_eq!(expected.longitude, request.longitude);
        assert_eq!(expected.exclude, request.exclude);
        assert_eq!(expected.extend, request.extend);
        assert_eq!(expected.lang, request.lang);
        assert_eq!(expected.units, request.units);
        assert_eq!(expected.url, request.url);

        assert_eq!(expected, request);
    }

    #[test]
    fn test_forecast_request_builder_simple() {
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        let request = ForecastRequestBuilder::new(API_KEY, LAT, LONG)
            .exclude_block(ExcludeBlock::Hourly)
            .exclude_blocks(&mut blocks)
            .extend(ExtendBy::Hourly)
            .lang(Lang::Arabic)
            .units(Units::Imperial)
            .build();

        let expected_url = {
            let mut url = Url::parse(&format!(
                "{base}/{key}/{lat:.16},{long:.16}",
                base = FORECAST_URL,
                key = API_KEY,
                lat = LAT,
                long = LONG
            )).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(EXTEND, "hourly")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            vec![
                ExcludeBlock::Hourly,
                ExcludeBlock::Daily,
                ExcludeBlock::Alerts
            ],
            Some(ExtendBy::Hourly),
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, request);
    }

    #[test]
    fn test_forecast_request_builder_complex() {
        let mut builder = ForecastRequestBuilder::new(API_KEY, LAT, LONG);
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        builder = builder.exclude_block(ExcludeBlock::Hourly);
        builder = builder.exclude_blocks(&mut blocks);
        builder = builder.extend(ExtendBy::Hourly);
        builder = builder.lang(Lang::Arabic);
        builder = builder.units(Units::Imperial);

        let expected_url = {
            let mut url = Url::parse(&format!(
                "{base}/{key}/{lat:.16},{long:.16}",
                base = FORECAST_URL,
                key = API_KEY,
                lat = LAT,
                long = LONG
            )).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(EXTEND, "hourly")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = ForecastRequest::new(
            API_KEY,
            LAT,
            LONG,
            expected_url,
            vec![
                ExcludeBlock::Hourly,
                ExcludeBlock::Daily,
                ExcludeBlock::Alerts
            ],
            Some(ExtendBy::Hourly),
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, builder.build());
    }

    #[test]
    fn test_time_machine_request_builder_defaults() {
        let request = TimeMachineRequestBuilder::new(
            API_KEY, LAT, LONG, TIME
        ).build();

        let expected_url = Url::parse(&format!(
            "{base}/{key}/{lat:.16},{long:.16},{time}?",
            base = FORECAST_URL,
            key = API_KEY,
            lat = LAT,
            long = LONG,
            time = TIME
        )).unwrap();

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            Vec::new(),
            None,
            None
        );

        assert_eq!(expected.api_key, request.api_key);
        assert_eq!(expected.latitude, request.latitude);
        assert_eq!(expected.longitude, request.longitude);
        assert_eq!(expected.time, request.time);
        assert_eq!(expected.exclude, request.exclude);
        assert_eq!(expected.lang, request.lang);
        assert_eq!(expected.units, request.units);
        assert_eq!(expected.url, request.url);

        assert_eq!(expected, request);
    }

    #[test]
    fn test_time_machine_request_builder_simple() {
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        let request = TimeMachineRequestBuilder::new(API_KEY, LAT, LONG, TIME)
            .exclude_block(ExcludeBlock::Hourly)
            .exclude_blocks(&mut blocks)
            .lang(Lang::Arabic)
            .units(Units::Imperial)
            .build();

        let expected_url = {
            let mut url = Url::parse(&format!(
                "{base}/{key}/{lat:.16},{long:.16},{time}",
                base = FORECAST_URL,
                key = API_KEY,
                lat = LAT,
                long = LONG,
                time = TIME
            )).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            vec![
                ExcludeBlock::Hourly,
                ExcludeBlock::Daily,
                ExcludeBlock::Alerts
            ],
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, request);
    }

    #[test]
    fn test_time_machine_request_builder_complex() {
        let mut builder = TimeMachineRequestBuilder::new(API_KEY, LAT, LONG, TIME);
        let mut blocks = vec![ExcludeBlock::Daily, ExcludeBlock::Alerts];

        builder = builder.exclude_block(ExcludeBlock::Hourly);
        builder = builder.exclude_blocks(&mut blocks);
        builder = builder.lang(Lang::Arabic);
        builder = builder.units(Units::Imperial);

        let expected_url = {
            let mut url = Url::parse(&format!(
                "{base}/{key}/{lat:.16},{long:.16},{time}",
                base = FORECAST_URL,
                key = API_KEY,
                lat = LAT,
                long = LONG,
                time = TIME
            )).unwrap();

            url.query_pairs_mut()
                .append_pair(EXCLUDE, "hourly,daily,alerts")
                .append_pair(LANG, "ar")
                .append_pair(UNITS, "us");

            url
        };

        let expected = TimeMachineRequest::new(
            API_KEY,
            LAT,
            LONG,
            TIME,
            expected_url,
            vec![
                ExcludeBlock::Hourly,
                ExcludeBlock::Daily,
                ExcludeBlock::Alerts
            ],
            Some(Lang::Arabic),
            Some(Units::Imperial)
        );

        assert_eq!(expected, builder.build());
    }
}