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
pub mod bus;
pub mod client;
pub mod crowd;
pub mod facility;
pub mod geo;
pub mod taxi;
pub mod traffic;
pub mod train;

use crate::{Client, LTAError, LTAResult};

pub use crate::r#async::client::LTAClient;

pub mod prelude {
    pub use crate::r#async::{
        bus::BusRequests, crowd::CrowdRequests, facility::FacilityRequests, geo::GeoRequests,
        taxi::TaxiRequests, traffic::TrafficRequests, train::TrainRequests,
    };
}

/// helper function to build request with skip
pub(crate) async fn build_req_with_skip<T, T2, C>(
    client: &C,
    url: &str,
    skip: Option<u32>,
) -> LTAResult<T2>
where
    C: Client<RB = reqwest::RequestBuilder>,
    for<'de> T: serde::Deserialize<'de> + Into<T2>,
{
    let skip = skip.unwrap_or(0);
    let rb = client.req_builder(url).query(&[("$skip", skip)]);

    let res = rb.send().await?;
    let res = handle_status_code(res).await?;
    Ok(res.json::<T>().await.map(Into::into)?)
}

/// helper function to build request with query
pub(crate) async fn build_req_with_query<T, T2, F, C>(
    client: &C,
    url: &str,
    query: F,
) -> LTAResult<T2>
where
    F: FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
    C: Client<RB = reqwest::RequestBuilder>,
    for<'de> T: serde::Deserialize<'de> + Into<T2>,
{
    let rb = client.req_builder(url);

    let res = query(rb).send().await?;
    let res = handle_status_code(res).await?;
    Ok(res.json::<T>().await.map(Into::into)?)
}

async fn handle_status_code(res: reqwest::Response) -> LTAResult<reqwest::Response> {
    use reqwest::StatusCode;
    let status_code = res.status();

    if status_code.is_success() {
        return Ok(res);
    }

    let body = res.text().await.map_err(|_| LTAError::FailedToParseBody)?;

    if body.contains("exceeded") {
        return Err(LTAError::RateLimitReached);
    }

    match status_code {
        StatusCode::UNAUTHORIZED => Err(LTAError::Unauthorized),
        StatusCode::NOT_FOUND => Err(LTAError::NotFound),
        _ => Err(LTAError::UnhandledStatusCode(status_code, body)),
    }
}

#[cfg(test)]
mod tests {
    use lta_models::prelude::MrtLine;

    use crate::models::geo::prelude::GeospatialLayerId;
    use crate::models::prelude::{StationCode, VolType};
    use crate::models::traffic::road::RoadDetailsType;
    use crate::prelude::*;
    use crate::r#async::prelude::*;
    use crate::{Client, LTAClient, LTAError, LTAResult};
    use std::env;

    macro_rules! gen_test {
        ($f: expr) => {{
            let client = get_client();
            let data = $f(&client, None).await?;
            println!("{:?}", data);
            Ok(())
        }};
    }

    fn get_client() -> LTAClient {
        let api_key = env::var("API_KEY").expect("API_KEY does not exist!");
        let client = LTAClient::with_api_key(api_key).unwrap();
        client
    }

    #[tokio::test]
    async fn get_bus_arrivals() -> LTAResult<()> {
        let client = get_client();
        let x = Bus::get_arrival(&client, 83139, None).await?;
        println!("{:?}", x);
        Ok(())
    }

    #[tokio::test]
    async fn get_bus_services() -> LTAResult<()> {
        gen_test!(Bus::get_bus_services)
    }

    #[tokio::test]
    async fn get_bus_routes() -> LTAResult<()> {
        gen_test!(Bus::get_bus_routes)
    }

    #[tokio::test]
    async fn get_bus_stops() -> LTAResult<()> {
        gen_test!(Bus::get_bus_stops)
    }

    #[ignore]
    #[tokio::test]
    async fn get_passenger_vol() -> LTAResult<()> {
        let client = get_client();
        let data = Crowd::get_passenger_vol_by(&client, VolType::OdBusStop, None, None).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[tokio::test]
    async fn get_taxi_avail() -> LTAResult<()> {
        gen_test!(Taxi::get_taxi_avail)
    }

    #[tokio::test]
    async fn get_taxi_stands() -> LTAResult<()> {
        gen_test!(Taxi::get_taxi_stands)
    }

    #[tokio::test]
    async fn get_erp_rates() -> LTAResult<()> {
        gen_test!(Traffic::get_erp_rates)
    }

    #[tokio::test]
    async fn get_cp_avail() -> LTAResult<()> {
        gen_test!(Traffic::get_carpark_avail)
    }

    #[tokio::test]
    async fn get_est_travel_time() -> LTAResult<()> {
        gen_test!(Traffic::get_est_travel_time)
    }

    #[tokio::test]
    async fn get_faulty_traffic_lights() -> LTAResult<()> {
        gen_test!(Traffic::get_faulty_traffic_lights)
    }

    #[tokio::test]
    async fn get_road_details() -> LTAResult<()> {
        let client = get_client();
        let data = Traffic::get_road_details(&client, RoadDetailsType::RoadWorks, None).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[tokio::test]
    async fn get_traffic_images() -> LTAResult<()> {
        gen_test!(Traffic::get_traffic_images)
    }

    #[tokio::test]
    async fn get_traffic_incidents() -> LTAResult<()> {
        gen_test!(Traffic::get_traffic_incidents)
    }

    #[tokio::test]
    async fn get_traffic_speed_band() -> LTAResult<()> {
        gen_test!(Traffic::get_traffic_speed_band)
    }

    #[tokio::test]
    async fn get_vms() -> LTAResult<()> {
        gen_test!(Traffic::get_vms_emas)
    }

    #[tokio::test]
    async fn get_bike_parking() -> LTAResult<()> {
        let client = get_client();
        let data = Traffic::get_bike_parking(&client, 1.364897, 103.766094, 15.0).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[ignore]
    #[tokio::test]
    async fn get_train_service_alerts() -> LTAResult<()> {
        let client = get_client();
        let x = Train::get_train_service_alert(&client, None).await;
        if let Err(e) = x {
            return match e {
                LTAError::RateLimitReached => Ok(()),
                _ => Err(e),
            };
        }
        Ok(())
    }

    #[tokio::test]
    async fn get_geospatial_whole_island() -> LTAResult<()> {
        let client = get_client();
        let data =
            Geo::get_geospatial_whole_island(&client, GeospatialLayerId::ArrowMarking).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[tokio::test]
    async fn get_facility_maintenance() -> LTAResult<()> {
        let client = get_client();
        let data = Facility::get_facilities_maintenance(&client, StationCode::BP1).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[tokio::test]
    async fn get_crowd_density_rt() -> LTAResult<()> {
        let client = get_client();
        let data = Crowd::get_crowd_density_rt(&client, MrtLine::BPL).await?;
        println!("{:?}", data);
        Ok(())
    }

    #[tokio::test]
    async fn get_crowd_density_forecast() -> LTAResult<()> {
        let client = get_client();
        let data = Crowd::get_crowd_density_forecast(&client, MrtLine::NSL).await;
        match data {
            Ok(d) => println!("{:?}", d),
            Err(e) => match e {
                LTAError::RateLimitReached => (),
                _ => panic!("{:?}", e),
            },
        }
        Ok(())
    }
}