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
use std::fmt;
use serde::{Serialize, Deserialize};
use crate::languages::Language;
use crate::units::Units;
use crate::responses::{OneCallResponse, HistoricalResponse, response_handler};

#[derive(Debug, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Copy, Clone)]
pub struct Fields {
    pub current: bool,
    pub minutely: bool,
    pub hourly: bool,
    pub daily: bool,
    pub alerts: bool,
}

impl fmt::Display for Fields {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Fields: current: {}, minutely: {}, hourly: {}, daily: {}, alerts: {}",
            self.current,
            self.minutely,
            self.hourly,
            self.daily,
            self.alerts
        )
    }
}

impl Default for Fields {
    fn default() -> Self {
        Self {
            current: true,
            minutely: true,
            hourly: true,
            daily: true,
            alerts: true,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Clone)]
pub struct OneCall {
    api_key: String,
    units: Units,
    language: Language,
    // fields are used to specify which should be included,
    // defaulting to true for all
    pub fields: Fields,
}

impl fmt::Display for OneCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "OneCall: (api_key: {}, units: {}, language: {}, fields: {}, methods: [new, get_onecall, get_historical])",
            self.api_key,
            self.units,
            self.language,
            self.fields
        )
    }
}

impl OneCall {
    pub fn new(api_key: String, units: Units, language: Language) -> Self {
        Self {
            api_key,
            units,
            language,
            fields: Fields {
                current: true,
                minutely: true,
                hourly: true,
                daily: true,
                alerts: true,
            },
        }
    }

    fn format_url_query(&self, lat: f64, lon: f64) -> String {
        format!(
            "https://api.openweathermap.org/data/3.0/onecall?lat={}&lon={}&units={}&lang={}&appid={}{}",
            lat,
            lon,
            self.units,
            self.language,
            self.api_key,
            self.format_excluded_fields()
        )
    }

    fn format_historical_query(&self, lat: f64, lon: f64, datetime: i64) -> String {
        format!(
            "https://api.openweathermap.org/data/3.0/onecall/timemachine?dt={}&lat={}&lon={}&units={}&lang={}&appid={}",
            datetime,
            lat,
            lon,
            self.units,
            self.language,
            self.api_key
        )
    }

    fn format_excluded_fields(&self) -> String {
        let mut excluded_fields = Vec::new();

        if !self.fields.current {
            excluded_fields.push("current")
        }
        if !self.fields.minutely {
            excluded_fields.push("minutely")
        }
        if !self.fields.hourly {
            excluded_fields.push("hourly")
        }
        if !self.fields.daily {
            excluded_fields.push("daily")
        }
        if !self.fields.alerts {
            excluded_fields.push("alerts")
        }

        if excluded_fields.is_empty() {
            "".to_string()
        } else {
            let mut excluded = "&exclude=".to_string();
            excluded.push_str(&excluded_fields.join(","));
            excluded
        }
    }

    pub async fn call(&self, lat: f64, lon: f64) -> Result<OneCallResponse, Box<dyn std::error::Error>> {
        let resp = reqwest::get(self.format_url_query(lat, lon))
            .await?;
        response_handler::<OneCallResponse>(resp).await
    }

    pub async fn call_historical_data(&self, lat: f64, lon: f64, datetime: i64) -> Result<HistoricalResponse, Box<dyn std::error::Error>> {
        let resp = reqwest::get(self.format_historical_query(lat, lon, datetime))
            .await?;
        response_handler::<HistoricalResponse>(resp).await
    }
}