1use log::debug;
2use quick_xml::de::from_str as from_xml_str;
3use reqwest::{get, StatusCode};
4use serde_json::from_str as from_json_str;
5
6use crate::{
7    error::{Error, Result},
8    prelude::OSM,
9    API_URL,
10};
11
12pub enum Format {
13    XML,
14    JSON,
15}
16pub async fn get_with_url(url: &str, format: Format) -> Result<OSM> {
17    debug!("GET {}", url);
18    let response = get(url).await?;
19    match response.status() {
20        StatusCode::OK => {
21            let text = response.text().await?;
22            debug!("response\n{}", text);
23            let osm: OSM = match format {
24                Format::XML => from_xml_str(&text)?,
25                Format::JSON => from_json_str(&text)?,
26            };
27
28            Ok(osm)
29        }
30        StatusCode::NOT_FOUND => Err(Error::Http(StatusCode::NOT_FOUND)),
31        _ => {
32            todo!("Handle other status codes")
33        }
34    }
35}
36
37pub async fn get_versions() -> Result<OSM> {
38    get_with_url(format!("{}/api/versions", API_URL).as_str(), Format::XML).await
39}
40
41#[cfg(feature = "json-api")]
42pub async fn get_versions_json() -> Result<OSM> {
43    get_with_url(
44        format!("{}/api/versions.json", API_URL).as_str(),
45        Format::JSON,
46    )
47    .await
48}
49
50pub async fn get_capabilities() -> Result<OSM> {
51    get_with_url(
52        format!("{}/api/capabilities", API_URL).as_str(),
53        Format::XML,
54    )
55    .await
56}
57
58pub async fn get_capabilities_json() -> Result<OSM> {
59    get_with_url(
60        format!("{}/api/capabilities.json", API_URL).as_str(),
61        Format::JSON,
62    )
63    .await
64}