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
use lazy_regex::regex;
use log::info;
use reqwest::blocking::Client;
use reqwest::Url;
use std::io::BufReader;

// See https://github.com/abrensch/brouter/blob/77977677db5fe78593c6a55afec6a251e69b3449/brouter-server/src/main/java/btools/server/request/ServerHandler.java#L17

#[derive(Debug, Clone)]
pub enum Nogo {
    Point(Point, f64),
    Line(Vec<Point>),
}

#[derive(Debug, Clone)]
pub struct Point {
    lat: f64,
    lon: f64,
}

#[derive(Debug)]
pub enum Error {
    InvalidGpx(String),
    Http(reqwest::Error),
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::InvalidGpx(s) => write!(f, "Invalid GPX: {}", s),
            Error::Http(e) => write!(f, "HTTP error: {}", e),
        }
    }
}

impl Point {
    pub fn new(lat: f64, lon: f64) -> Self {
        Point { lat, lon }
    }

    pub fn lat(&self) -> f64 {
        self.lat
    }

    pub fn lon(&self) -> f64 {
        self.lon
    }
}

pub struct Brouter {
    client: Client,
    base_url: Url,
}

impl Default for Brouter {
    fn default() -> Self {
        Self::new("http://localhost:17777")
    }
}

impl Brouter {
    pub fn new(base_url: &str) -> Self {
        Brouter {
            client: Client::new(),
            base_url: Url::parse(base_url).unwrap(),
        }
    }

    pub fn upload_profile(&self, profile: &str, data: Vec<u8>) -> Result<(), Error> {
        let url = self
            .base_url
            .join("brouter/profile")
            .unwrap()
            .join(profile)
            .unwrap();

        let response = self
            .client
            .post(url)
            .body(data)
            .send()
            .map_err(Error::Http)?;

        response.error_for_status().map_err(Error::Http).map(|_| ())
    }

    pub fn broute(
        &self,
        points: &[Point],
        nogos: &[Nogo],
        profile: &str,
        alternativeidx: Option<u8>,
        name: Option<&str>,
    ) -> Result<gpx::Gpx, Error> {
        let lon_lat_strings: Vec<String> = points
            .iter()
            .map(|p| format!("{},{}", p.lon(), p.lat()))
            .collect();

        info!("Planning route along {:?}", points);

        let lonlats = lon_lat_strings.join("%7C");

        let nogos_string: String = nogos
            .iter()
            .filter_map(|nogo| match nogo {
                Nogo::Point(p, radius) => Some(format!("{},{},{}", p.lon(), p.lat(), radius)),
                Nogo::Line(_) => None,
            })
            .collect::<Vec<_>>()
            .join("%7C");

        let polylines = nogos
            .iter()
            .filter_map(|nogo| match nogo {
                Nogo::Point(_, _) => None,
                Nogo::Line(points) => {
                    let lat_lon_strings: Vec<String> = points
                        .iter()
                        .map(|p| format!("{},{}", p.lon(), p.lat()))
                        .collect();
                    Some(lat_lon_strings.join(","))
                }
            })
            .collect::<Vec<_>>()
            .join("%7C");

        let alternativeidx = alternativeidx.unwrap_or(0);

        assert!((0..=3).contains(&alternativeidx));

        let mut url = self.base_url.join("brouter").unwrap();

        url.query_pairs_mut()
            .append_pair("lonlats", &lonlats)
            .append_pair("profile", profile)
            .append_pair("alternativeidx", &alternativeidx.to_string())
            .append_pair("format", "gpx")
            .append_pair("timode", "3")
            .append_pair("nogos", &nogos_string)
            .append_pair("polylines", &polylines);

        if let Some(name) = name {
            url.query_pairs_mut().append_pair("trackname", name);
        }

        let response = self
            .client
            .get(url)
            .timeout(std::time::Duration::from_secs(3600))
            .send()
            .map_err(Error::Http)?
            .error_for_status()
            .map_err(Error::Http)?;

        let text = response.bytes().map_err(Error::Http)?.to_vec();

        if let Some(m) = regex!("datafile (.*) not found\n"B).captures(text.as_slice()) {
            panic!(
                "datafile {} not found",
                String::from_utf8_lossy(m.get(1).unwrap().as_bytes())
            );
        }

        let gpx: gpx::Gpx = gpx::read(BufReader::new(text.as_slice())).map_err(|_e| {
            Error::InvalidGpx(String::from_utf8_lossy(text.as_slice()).to_string())
        })?;

        Ok(gpx)
    }
}