1use std::fmt::Display;
2use chrono::{DateTime, TimeZone, Timelike};
3
4use super::BaseApi;
5use crate::{Client, Query, Language, History};
6
7
8pub struct HistoryApi<'a, Tz: TimeZone>
9where
10 Tz::Offset: Display
11{
12 client: &'a Client,
13 query: Option<Query>,
14 dt: Option<DateTime<Tz>>,
15 end_dt: Option<DateTime<Tz>>,
16 hour: bool,
17 lang: Option<Language>
18}
19
20impl<'a, Tz: TimeZone> HistoryApi<'a, Tz>
21where
22 Tz::Offset: Display,
23{
24 /// Use [`crate::Client`]
25 pub fn new(client: &'a Client) -> Self {
26 Self {
27 client,
28 query: None,
29 dt: None,
30 end_dt: None,
31 hour: false,
32 lang: None
33 }
34 }
35
36 /// Set up the query
37 ///
38 /// Query parameter based on which data is sent back
39 pub fn query(mut self, query: Query) -> Self {
40 self.query = Some(query);
41 self
42 }
43
44 /// Set up a datetime
45 ///
46 /// `dt` should be on or after 1st Jan, 2010
47 pub fn dt(mut self, dt: DateTime<Tz>) -> Self {
48 self.dt = Some(dt);
49 self
50 }
51
52 /// Set up a end datetime
53 ///
54 /// `end_dt` should be on or after 1st Jan, 2010 and should be greater than `dt` parameter and difference should not be more than 30 days between the two dates.
55 pub fn end_dt(mut self, end_dt: DateTime<Tz>) -> Self {
56 self.end_dt = Some(end_dt);
57 self
58 }
59
60 /// Set up use hour
61 ///
62 /// Time is extracted from dt
63 pub fn hour(mut self) -> Self {
64 self.hour = true;
65 self
66 }
67
68 /// Set up language
69 ///
70 /// `condition:text` field in API in the desired language
71 pub fn lang(mut self, lang: Language) -> Self {
72 self.lang = Some(lang);
73 self
74 }
75}
76
77impl<'a, Tz: TimeZone> BaseApi<'a> for HistoryApi<'a, Tz>
78where
79 Tz::Offset: Display,
80{
81 type Model = History;
82
83 fn path(&self) -> &str {
84 "history"
85 }
86
87 fn client(&self) -> &'a Client {
88 self.client
89 }
90
91 fn params(&self) -> Vec<(&str, String)> {
92 let query = self.query.as_ref().unwrap();
93 let dt = self.dt.as_ref().unwrap();
94
95 let mut params = vec![
96 ("key", self.client.api_key.clone()), ("q", query.to_string()),
97 ("dt", format!("{}", dt.format("%Y-%m-%d"))),
98 ];
99
100 if let Some(end_dt) = &self.end_dt {
101 params.push(("end_dt", format!("{}", end_dt.format("%Y-%m-%d"))))
102 }
103
104 if self.hour {
105 params.push(("hour", dt.hour().to_string()))
106 }
107
108 if let Some(lang) = &self.lang {
109 params.push(("lang", lang.to_string()))
110 }
111
112 params
113 }
114}
115