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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use std::collections::BTreeMap;

use abstio::{CityName, Manifest, MapName};
use geom::{Distance, Percent};
use map_model::City;
use widgetry::tools::FileLoader;
use widgetry::{
    lctrl, Autocomplete, ClickOutcome, ControlState, DrawBaselayer, DrawWithTooltips, EventCtx,
    GeomBatch, GfxCtx, Image, Key, Line, Outcome, Panel, PanelDims, RewriteColor, State, Text,
    TextExt, Transition, Widget,
};

use crate::load::MapLoader;
use crate::render::DrawArea;
use crate::tools::{grey_out_map, nice_country_name, nice_map_name};
use crate::AppLike;

/// Lets the player switch maps.
pub struct CityPicker<A: AppLike> {
    panel: Panel,
    // Wrapped in an Option just to make calling from event() work.
    on_load: Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> CityPicker<A> {
    pub fn new_state(
        ctx: &mut EventCtx,
        app: &A,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        let city = app.map().get_city_name().clone();
        CityPicker::new_in_city(ctx, on_load, city)
    }

    fn new_in_city(
        ctx: &mut EventCtx,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
        city_name: CityName,
    ) -> Box<dyn State<A>> {
        FileLoader::<A, City>::new_state(
            ctx,
            abstio::path(format!(
                "system/{}/{}/city.bin",
                city_name.country, city_name.city
            )),
            Box::new(move |ctx, app, _, maybe_city| {
                // If city.bin exists, use it to draw the district map.
                let district_picker = if let Ok(city) = maybe_city {
                    let bounds = city.boundary.get_bounds();

                    let zoom = (0.8 * ctx.canvas.window_width / bounds.width())
                        .min(0.8 * ctx.canvas.window_height / bounds.height());

                    let mut batch = GeomBatch::new();
                    batch.push(app.cs().map_background.clone(), city.boundary);
                    for (area_type, polygon) in city.areas {
                        batch.push(DrawArea::fill(area_type, app.cs()), polygon);
                    }

                    // If somebody has just generated a new map somewhere with an existing
                    // city.bin, but hasn't updated city.bin yet, that new map will be invisible on
                    // the city-wide diagram.
                    let outline_color = app.cs().minimap_cursor_border;
                    let mut tooltips = Vec::new();
                    for (name, polygon) in city.districts {
                        if &name != app.map().get_name() {
                            batch.push(
                                outline_color,
                                polygon.to_outline(Distance::meters(200.0)).unwrap(),
                            );
                            let polygon = polygon.scale(zoom);
                            tooltips.push((
                                polygon.clone(),
                                Text::from(nice_map_name(&name)),
                                Some(ClickOutcome::Custom(Box::new(name))),
                            ));
                        }
                    }
                    DrawWithTooltips::new_widget(
                        ctx,
                        batch.scale(zoom),
                        tooltips,
                        Box::new(move |poly| {
                            GeomBatch::from(vec![(outline_color.alpha(0.5), poly.clone())])
                        }),
                    )
                } else {
                    Widget::nothing()
                };

                // Use the filesystem to list the buttons on the side.
                // (There's no point in listing these from city.bin if it exists -- if somebody
                // imports a new map in an existing city, it could be out of sync anyway.)
                let mut this_city =
                    vec![format!("More districts in {}", city_name.describe()).text_widget(ctx)];
                for name in MapName::list_all_maps_in_city_merged(&city_name, &Manifest::load()) {
                    this_city.push(
                        ctx.style()
                            .btn_outline
                            .text(nice_map_name(&name))
                            .no_tooltip()
                            .disabled(&name == app.map().get_name())
                            .build_widget(ctx, &name.path()),
                    );
                }

                let mut other_places = vec![Line("Other places").into_widget(ctx)];
                for (country, cities) in cities_per_country() {
                    // If there's only one city and we're already there, skip it.
                    if cities.len() == 1 && cities[0] == city_name {
                        continue;
                    }
                    let flag_path = format!("system/assets/flags/{}.svg", country);
                    if abstio::file_exists(abstio::path(&flag_path)) {
                        other_places.push(
                            ctx.style()
                                .btn_outline
                                .icon_text(
                                    &flag_path,
                                    format!("{} in {}", cities.len(), nice_country_name(&country)),
                                )
                                .image_color(RewriteColor::NoOp, ControlState::Default)
                                .image_dims(30.0)
                                .build_widget(ctx, &country),
                        );
                    } else {
                        other_places.push(
                            ctx.style()
                                .btn_outline
                                .text(format!(
                                    "{} in {}",
                                    cities.len(),
                                    nice_country_name(&country)
                                ))
                                .build_widget(ctx, country),
                        );
                    }
                }

                Transition::Replace(Box::new(CityPicker {
                    on_load: Some(on_load),
                    panel: Panel::new_builder(Widget::col(vec![
                        Widget::row(vec![
                            Line("Select a district").small_heading().into_widget(ctx),
                            ctx.style().btn_close_widget(ctx),
                        ]),
                        if cfg!(target_arch = "wasm32") {
                            // On web, this is a link, so it's styled appropriately.
                            ctx.style()
                                .btn_plain
                                .btn()
                                .label_underlined_text("Import a new city into A/B Street")
                                .build_widget(ctx, "import new city")
                        } else {
                            // On native this shows the "import" instructions modal within
                            // the app
                            Widget::row(vec![
                                ctx.style()
                                    .btn_outline
                                    .text("Import a new city into A/B Street")
                                    .build_widget(ctx, "import new city"),
                                ctx.style()
                                    .btn_outline
                                    .text("Re-import this map with latest OpenStreetMap data")
                                    .tooltip("OSM edits take a few minutes to appear in Overpass. Note this will create a new copy of the map, not overwrite the original.")
                                    .build_widget(ctx, "re-import this city"),
                            ])
                        },
                        ctx.style()
                            .btn_outline
                            .icon_text("system/assets/tools/search.svg", "Search all maps")
                            .hotkey(lctrl(Key::F))
                            .build_def(ctx),
                        Widget::row(vec![
                            Widget::col(other_places).centered_vert(),
                            district_picker,
                            Widget::col(this_city).centered_vert(),
                        ]),
                    ]))
                    .build(ctx),
                }))
            }),
        )
    }
}

impl<A: AppLike + 'static> State<A> for CityPicker<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        // TODO This happens if we prompt the user to download something, but they cancel. At that
        // point, we've lost the callback, so for now, just totally bail out.
        if self.on_load.is_none() {
            return Transition::Pop;
        }

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                "Search all maps" => {
                    return Transition::Replace(AllCityPicker::new_state(
                        ctx,
                        self.on_load.take().unwrap(),
                    ));
                }
                "import new city" => {
                    #[cfg(target_arch = "wasm32")]
                    {
                        widgetry::tools::open_browser(
                            "https://a-b-street.github.io/docs/user/new_city.html",
                        );
                    }
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        return Transition::Replace(crate::tools::importer::ImportCity::new_state(
                            ctx,
                            self.on_load.take().unwrap(),
                        ));
                    }
                }
                "re-import this city" => {
                    #[cfg(target_arch = "wasm32")]
                    {
                        unreachable!()
                    }
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        return reimport_city(ctx, app);
                    }
                }
                x => {
                    if let Some(name) = MapName::from_path(x) {
                        return chose_city(ctx, app, name, &mut self.on_load);
                    }
                    // Browse cities for another country
                    return Transition::Replace(CitiesInCountryPicker::new_state(
                        ctx,
                        app,
                        self.on_load.take().unwrap(),
                        x,
                    ));
                }
            },
            Outcome::ClickCustom(data) => {
                let name = data.as_any().downcast_ref::<MapName>().unwrap();
                return chose_city(ctx, app, name.clone(), &mut self.on_load);
            }
            _ => {}
        }

        Transition::Keep
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::PreviousState
    }

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}

struct AllCityPicker<A: AppLike> {
    panel: Panel,
    // Wrapped in an Option just to make calling from event() work.
    on_load: Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> AllCityPicker<A> {
    fn new_state(
        ctx: &mut EventCtx,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        let mut autocomplete_entries = Vec::new();
        for name in MapName::list_all_maps_merged(&Manifest::load()) {
            autocomplete_entries.push((name.describe(), name.path()));
        }

        Box::new(AllCityPicker {
            on_load: Some(on_load),
            panel: Panel::new_builder(Widget::col(vec![
                Widget::row(vec![
                    Line("Select a district").small_heading().into_widget(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                Widget::row(vec![
                    Image::from_path("system/assets/tools/search.svg").into_widget(ctx),
                    Autocomplete::new_widget(ctx, autocomplete_entries, 10).named("search"),
                ])
                .padding(8),
            ]))
            .dims_width(PanelDims::ExactPercent(0.8))
            .dims_height(PanelDims::ExactPercent(0.8))
            .build(ctx),
        })
    }
}

impl<A: AppLike + 'static> State<A> for AllCityPicker<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        // Same as CityPicker
        if self.on_load.is_none() {
            return Transition::Pop;
        }

        if let Outcome::Clicked(x) = self.panel.event(ctx) {
            match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                _ => unreachable!(),
            }
        }
        if let Some(mut paths) = self.panel.autocomplete_done::<String>("search") {
            if !paths.is_empty() {
                return chose_city(
                    ctx,
                    app,
                    MapName::from_path(&paths.remove(0)).unwrap(),
                    &mut self.on_load,
                );
            }
        }

        Transition::Keep
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::PreviousState
    }

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}

struct CitiesInCountryPicker<A: AppLike> {
    panel: Panel,
    // Wrapped in an Option just to make calling from event() work.
    on_load: Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> CitiesInCountryPicker<A> {
    fn new_state(
        ctx: &mut EventCtx,
        app: &A,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
        country: &str,
    ) -> Box<dyn State<A>> {
        let flag_path = format!("system/assets/flags/{}.svg", country);
        let draw_flag = if abstio::file_exists(abstio::path(&flag_path)) {
            let flag = GeomBatch::load_svg(ctx, format!("system/assets/flags/{}.svg", country));
            let y_factor = 30.0 / flag.get_dims().height;
            flag.scale(y_factor).into_widget(ctx)
        } else {
            Widget::nothing()
        };
        let mut col = vec![Widget::row(vec![
            draw_flag,
            Line(format!("Select a city in {}", nice_country_name(country)))
                .small_heading()
                .into_widget(ctx),
            ctx.style().btn_close_widget(ctx),
        ])];

        let mut buttons = Vec::new();
        let mut last_letter = ' ';
        for city in cities_per_country().remove(country).unwrap() {
            if &city == app.map().get_city_name() {
                continue;
            }
            let letter = city
                .city
                .chars()
                .next()
                .unwrap()
                .to_uppercase()
                .next()
                .unwrap();
            if last_letter != letter {
                if !buttons.is_empty() {
                    let mut row = vec![Line(last_letter)
                        .small_heading()
                        .into_widget(ctx)
                        .margin_right(20)];
                    row.append(&mut buttons);
                    col.push(
                        Widget::custom_row(row).flex_wrap_no_inner_spacing(ctx, Percent::int(70)),
                    );
                }

                last_letter = letter;
            }

            buttons.push(
                ctx.style()
                    .btn_outline
                    .text(&city.city)
                    .build_widget(ctx, &city.to_path())
                    .margin_right(10)
                    .margin_below(10),
            );
        }
        if !buttons.is_empty() {
            let mut row = vec![Line(last_letter)
                .small_heading()
                .into_widget(ctx)
                .margin_right(20)];
            row.append(&mut buttons);
            col.push(Widget::custom_row(row).flex_wrap_no_inner_spacing(ctx, Percent::int(70)));
        }

        Box::new(CitiesInCountryPicker {
            on_load: Some(on_load),
            panel: Panel::new_builder(Widget::col(col))
                .dims_width(PanelDims::ExactPercent(0.8))
                .dims_height(PanelDims::ExactPercent(0.8))
                .build(ctx),
        })
    }
}

impl<A: AppLike + 'static> State<A> for CitiesInCountryPicker<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        // Same as CityPicker
        if self.on_load.is_none() {
            return Transition::Pop;
        }

        if let Outcome::Clicked(x) = self.panel.event(ctx) {
            match x.as_ref() {
                "close" => {
                    // Go back to the screen that lets you choose all countries.
                    return Transition::Replace(CityPicker::new_state(
                        ctx,
                        app,
                        self.on_load.take().unwrap(),
                    ));
                }
                path => {
                    let city = CityName::parse(path).unwrap();
                    let mut maps = MapName::list_all_maps_in_city_merged(&city, &Manifest::load());
                    if maps.len() == 1 {
                        return chose_city(ctx, app, maps.pop().unwrap(), &mut self.on_load);
                    }

                    // We may need to grab city.bin
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        let path = format!("system/{}/{}/city.bin", city.country, city.city);
                        if Manifest::load()
                            .entries
                            .contains_key(&format!("data/{}", path))
                            && !abstio::file_exists(abstio::path(path))
                        {
                            return crate::tools::prompt_to_download_missing_data(
                                ctx,
                                maps.pop().unwrap(),
                                self.on_load.take().unwrap(),
                            );
                        }
                    }

                    return Transition::Replace(CityPicker::new_in_city(
                        ctx,
                        self.on_load.take().unwrap(),
                        city,
                    ));
                }
            }
        }

        Transition::Keep
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::PreviousState
    }

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}

fn cities_per_country() -> BTreeMap<String, Vec<CityName>> {
    let mut per_country = BTreeMap::new();
    for city in CityName::list_all_cities_merged(&Manifest::load()) {
        per_country
            .entry(city.country.clone())
            .or_insert_with(Vec::new)
            .push(city);
    }
    per_country
}

fn chose_city<A: AppLike + 'static>(
    ctx: &mut EventCtx,
    app: &mut A,
    name: MapName,
    on_load: &mut Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
) -> Transition<A> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        if !abstio::file_exists(name.path()) {
            let on_load = on_load.take().unwrap();
            return crate::tools::prompt_to_download_missing_data(
                ctx,
                name.clone(),
                Box::new(move |ctx, app| {
                    Transition::Replace(MapLoader::new_state(ctx, app, name, on_load))
                }),
            );
        }
    }

    Transition::Replace(MapLoader::new_state(
        ctx,
        app,
        name,
        on_load.take().unwrap(),
    ))
}

#[cfg(not(target_arch = "wasm32"))]
fn reimport_city<A: AppLike + 'static>(ctx: &mut EventCtx, app: &A) -> Transition<A> {
    let name = format!("updated_{}", app.map().get_name().as_filename());

    let mut args = vec![
        crate::tools::find_exe("cli"),
        "one-step-import".to_string(),
        "--geojson-path=boundary.json".to_string(),
        format!("--map-name={}", name),
    ];
    if app.map().get_config().driving_side == map_model::DrivingSide::Left {
        args.push("--drive-on-left".to_string());
    }

    // Write the current map boundary
    abstio::write_json(
        "boundary.json".to_string(),
        &geom::geometries_to_geojson(vec![app
            .map()
            .get_boundary_polygon()
            .to_geojson(Some(app.map().get_gps_bounds()))]),
    );

    return Transition::Push(crate::tools::RunCommand::new_state(
        ctx,
        true,
        args,
        Box::new(|_, _, success, _| {
            if success {
                abstio::delete_file("boundary.json");

                Transition::ConsumeState(Box::new(move |state, ctx, app| {
                    let mut state = state.downcast::<CityPicker<A>>().ok().unwrap();
                    let on_load = state.on_load.take().unwrap();
                    let map_name = MapName::new("zz", "oneshot", &name);
                    vec![MapLoader::new_state(ctx, app, map_name, on_load)]
                }))
            } else {
                // The popup already explained the failure
                Transition::Keep
            }
        }),
    ));
}