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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
#![no_std]
#![deny(missing_docs)]
//! The `s2-tilejson` Rust crate... TODO

extern crate alloc;

use serde::{Serialize, Deserialize, Serializer, Deserializer};
use serde::ser::SerializeTuple;
use serde::de::{self, SeqAccess, Visitor};

use alloc::borrow::ToOwned;
use alloc::collections::BTreeSet;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use alloc::fmt;

/// S2 Face
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Face {
    /// Face 0
    Face0 = 0,
    /// Face 1
    Face1 = 1,
    /// Face 2
    Face2 = 2,
    /// Face 3
    Face3 = 3,
    /// Face 4
    Face4 = 4,
    /// Face 5
    Face5 = 5,
}
impl From<Face> for u8 {
    fn from(face: Face) -> Self {
        face as u8
    }
}
impl From<u8> for Face {
    fn from(face: u8) -> Self {
        match face {
            1 => Face::Face1,
            2 => Face::Face2,
            3 => Face::Face3,
            4 => Face::Face4,
            5 => Face::Face5,
            _ => Face::Face0,
        }
    }
}

/// The Bounding box, whether the tile bounds or lon-lat bounds or whatever.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct BBox<T = f64> {
    /// left most point; Also represents the left-most longitude
    pub left: T,
    /// bottom most point; Also represents the bottom-most latitude
    pub bottom: T,
    /// right most point; Also represents the right-most longitude
    pub right: T,
    /// top most point; Also represents the top-most latitude
    pub top: T,
}
impl<T> Serialize for BBox<T>
where
    T: Serialize + Copy,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_tuple(4)?;
        seq.serialize_element(&self.left)?;
        seq.serialize_element(&self.bottom)?;
        seq.serialize_element(&self.right)?;
        seq.serialize_element(&self.top)?;
        seq.end()
    }
}

impl<'de, T> Deserialize<'de> for BBox<T>
where
    T: Deserialize<'de> + Copy,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct BBoxVisitor<T> {
            marker: core::marker::PhantomData<T>,
        }

        impl<'de, T> Visitor<'de> for BBoxVisitor<T>
        where
            T: Deserialize<'de> + Copy,
        {
            type Value = BBox<T>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a sequence of four numbers")
            }

            fn visit_seq<V>(self, mut seq: V) -> Result<BBox<T>, V::Error>
            where
                V: SeqAccess<'de>,
            {
                let left = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let bottom = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                let right = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(2, &self))?;
                let top = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(3, &self))?;
                Ok(BBox { left, bottom, right, top })
            }
        }

        deserializer.deserialize_tuple(4, BBoxVisitor { marker: core::marker::PhantomData })
    }
}

/// Use bounds as floating point numbers for longitude and latitude
pub type LonLatBounds = BBox<f64>;

/// Use bounds as u64 for the tile index range
pub type TileBounds = BBox<u64>;

/// 1: points, 2: lines, 3: polys, 4: points3D, 5: lines3D, 6: polys3D
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
pub enum DrawType {
    /// Collection of points
    Points = 1,
    /// Collection of lines
    Lines = 2,
    /// Collection of polygons
    Polygons = 3,
    /// Collection of 3D points
    Points3D = 4,
    /// Collection of 3D lines
    Lines3D = 5,
    /// Collection of 3D polygons
    Polygons3D = 6,
}

// Shapes exist solely to deconstruct and rebuild objects.
//
// Shape limitations:
// - all keys are strings.
// - all values are either:
// - - primitive types: strings, numbers (f32, f64, u64, i64), true, false, or null
// - - sub types: an array of a shape or a nested object which is itself a shape
// - - if the sub type is an array, ensure all elements are of the same type
// The interfaces below help describe how shapes are built by the user.

/// Primitive types that can be found in a shape
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PrimitiveShape {
    /// String type utf8 encoded
    String,
    /// unsigned 64 bit integer
    U64,
    /// signed 64 bit integer
    I64,
    /// floating point number
    F32,
    /// double precision floating point number
    F64,
    /// boolean
    Bool,
    /// null
    Null,
}

/// Arrays may contain either a primitive or an object whose values are primitives
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum ShapePrimitiveType {
    /// Primitive type
    Primitive(PrimitiveShape),
    /// Nested shape that can only contain primitives
    NestedPrimitive(BTreeMap<String, PrimitiveShape>),
}

/// Shape types that can be found in a shapes object.
/// Either a primitive, an array containing any type, or a nested shape.
/// If the type is an array, all elements must be the same type
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum ShapeType {
    /// Primitive type
    Primitive(PrimitiveShape),
    /// Nested shape that can only contain primitives
    Array(Vec<ShapePrimitiveType>),
    /// Nested shape
    Nested(Shape),
}

/// The Shape Object
pub type Shape = BTreeMap<String, ShapeType>;

/// Each layer has metadata associated with it. Defined as blueprints pre-construction of vector data.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LayerMetaData {
    /// The description of the layer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// the lowest zoom level at which the layer is available
    pub minzoom: u8,
    /// the highest zoom level at which the layer is available
    pub maxzoom: u8,
    /// The draw types that can be found in this layer
    pub draw_types: Vec<DrawType>,
    /// The shape that can be found in this layer
    pub shape: Shape,
    /// The shape used inside features that can be found in this layer
    #[serde(skip_serializing_if = "Option::is_none", rename = "mShape")]
    pub m_shape: Option<Shape>,
}

/// Each layer has metadata associated with it. Defined as blueprints pre-construction of vector data.
pub type LayersMetaData = BTreeMap<String, LayerMetaData>;

/// Tilestats is simply a tracker to see where most of the tiles live
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct TileStatsMetadata {
    /// total number of tiles
    pub total: u64,
    /// number of tiles for face 0
    #[serde(rename = "0")]
    pub total_0: u64,
    /// number of tiles for face 1
    #[serde(rename = "1")]
    pub total_1: u64,
    /// number of tiles for face 2
    #[serde(rename = "2")]
    pub total_2: u64,
    /// number of tiles for face 3
    #[serde(rename = "3")]
    pub total_3: u64,
    /// number of tiles for face 4
    #[serde(rename = "4")]
    pub total_4: u64,
    /// number of tiles for face 5
    #[serde(rename = "5")]
    pub total_5: u64,
}
impl TileStatsMetadata {
    /// Access the total number of tiles for a given face
    pub fn get(&self, face: Face) -> u64 {
        match face {
            Face::Face0 => self.total_0,
            Face::Face1 => self.total_1,
            Face::Face2 => self.total_2,
            Face::Face3 => self.total_3,
            Face::Face4 => self.total_4,
            Face::Face5 => self.total_5,
        }
    }

    /// Increment the total number of tiles for a given face and also the grand total
    pub fn increment(&mut self, face: Face) {
        match face {
            Face::Face0 => self.total_0 += 1,
            Face::Face1 => self.total_1 += 1,
            Face::Face2 => self.total_2 += 1,
            Face::Face3 => self.total_3 += 1,
            Face::Face4 => self.total_4 += 1,
            Face::Face5 => self.total_5 += 1,
        }
        self.total += 1;
    }
}

/// Attribution data is stored in an object.
/// The key is the name of the attribution, and the value is the link
pub type Attribution = BTreeMap<String, String>;

/// Track the S2 tile bounds of each face and zoom
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct FaceBounds {
    // facesbounds[face][zoom] = [...]
    /// Tile bounds for face 0 at each zoom
    #[serde(rename = "0")]
    pub face0: BTreeMap<u8, TileBounds>,
    /// Tile bounds for face 1 at each zoom
    #[serde(rename = "1")]
    pub face1: BTreeMap<u8, TileBounds>,
    /// Tile bounds for face 2 at each zoom
    #[serde(rename = "2")]
    pub face2: BTreeMap<u8, TileBounds>,
    /// Tile bounds for face 3 at each zoom
    #[serde(rename = "3")]
    pub face3: BTreeMap<u8, TileBounds>,
    /// Tile bounds for face 4 at each zoom
    #[serde(rename = "4")]
    pub face4: BTreeMap<u8, TileBounds>,
    /// Tile bounds for face 5 at each zoom
    #[serde(rename = "5")]
    pub face5: BTreeMap<u8, TileBounds>,
}
impl FaceBounds {
    /// Access the tile bounds for a given face and zoom
    pub fn get(&self, face: Face) -> &BTreeMap<u8, TileBounds> {
        match face {
            Face::Face0 => &self.face0,
            Face::Face1 => &self.face1,
            Face::Face2 => &self.face2,
            Face::Face3 => &self.face3,
            Face::Face4 => &self.face4,
            Face::Face5 => &self.face5,
        }
    }

    /// Access the mutable tile bounds for a given face and zoom
    pub fn get_mut(&mut self, face: Face) -> &mut BTreeMap<u8, TileBounds> {
        match face {
            Face::Face0 => &mut self.face0,
            Face::Face1 => &mut self.face1,
            Face::Face2 => &mut self.face2,
            Face::Face3 => &mut self.face3,
            Face::Face4 => &mut self.face4,
            Face::Face5 => &mut self.face5,
        }
    }
}

/// Track the WM tile bounds of each zoom
/// `[zoom: number]: BBox`
pub type WMBounds = BTreeMap<u8, TileBounds>;

/// Check the source type of the layer
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SourceType {
    /// Vector data
    #[default] Vector,
    /// Json data
    Json,
    /// Raster data
    Raster,
    /// Raster DEM data
    #[serde(rename = "raster-dem")]
    RasterDem,
    /// Sensor data
    Sensor,
    /// Unknown source type
    Unknown,
}
impl From<&str> for SourceType {
    fn from(source_type: &str) -> Self {
        match source_type {
            "vector" => SourceType::Vector,
            "json" => SourceType::Json,
            "raster" => SourceType::Raster,
            "raster-dem" => SourceType::RasterDem,
            "sensor" => SourceType::Sensor,
            _ => SourceType::Unknown,
        }
    }
}

/// Store the encoding of the data
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Encoding {
    /// Gzip encoding
    Gzip,
    /// Brotli encoding
    #[serde(rename = "br")]
    Brotli,
    /// Zstd encoding
    Zstd,
    /// No encoding
    #[default] None,
}
impl From<u8> for Encoding {
    fn from(encoding: u8) -> Self {
        match encoding {
            1 => Encoding::Gzip,
            2 => Encoding::Brotli,
            3 => Encoding::Zstd,
            _ => Encoding::None,
        }
    }
}
impl From<Encoding> for u8 {
    fn from(encoding: Encoding) -> Self {
        match encoding {
            Encoding::Gzip => 1,
            Encoding::Brotli => 2,
            Encoding::Zstd => 3,
            Encoding::None => 0,
        }
    }
}
impl From<Encoding> for String {
    fn from(encoding: Encoding) -> Self {
        match encoding {
            Encoding::Gzip => "gzip".into(),
            Encoding::Brotli => "br".into(),
            Encoding::Zstd => "zstd".into(),
            Encoding::None => "none".into(),
        }
    }
}
impl From<&str> for Encoding {
    fn from(encoding: &str) -> Self {
        match encoding {
            "gzip" => Encoding::Gzip,
            "br" => Encoding::Brotli,
            "zstd" => Encoding::Zstd,
            _ => Encoding::None,
        }
    }
}

/// Old spec tracks basic vector data
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct VectorLayer {
    /// The id of the layer
    pub id: String,
    /// The description of the layer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The min zoom of the layer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minzoom: Option<u8>,
    /// The max zoom of the layer
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maxzoom: Option<u8>,
    /// Information about each field property
    pub fields: BTreeMap<String, String>
}

/// Default S2 tile scheme is `fzxy`
/// Default Web Mercator tile scheme is `xyz`
/// Adding a t prefix to the scheme will change the request to be time sensitive
/// TMS is an oudated version that is not supported by s2maps-gpu
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Scheme {
    /// The default scheme with faces (S2)
    #[default] Fzxy,
    /// The time sensitive scheme with faces (S2)
    Tfzxy,
    /// The basic scheme (Web Mercator)
    Xyz,
    /// The time sensitive basic scheme (Web Mercator)
    Txyz,
    /// The TMS scheme
    Tms,
}
impl From<&str> for Scheme {
    fn from(scheme: &str) -> Self {
        match scheme {
            "fzxy" => Scheme::Fzxy,
            "tfzxy" => Scheme::Tfzxy,
            "xyz" => Scheme::Xyz,
            "txyz" => Scheme::Txyz,
            _ => Scheme::Tms,
        }
    }
}
impl From<Scheme> for String {
    fn from(scheme: Scheme) -> Self {
        match scheme {
            Scheme::Fzxy => "fzxy".into(),
            Scheme::Tfzxy => "tfzxy".into(),
            Scheme::Xyz => "xyz".into(),
            Scheme::Txyz => "txyz".into(),
            Scheme::Tms => "tms".into(),
        }
    }
}

/// Store where the center of the data lives
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct Center {
    /// The longitude of the center
    pub lon: f64,
    /// The latitude of the center
    pub lat: f64,
    /// The zoom of the center
    pub zoom: u8,
}

/// Metadata for the tile data
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Metadata {
    /// The version of the s2-tilejson spec
    pub s2tilejson: String,
    /// The version of the data
    pub version: String,
    /// The name of the data
    pub name: String,
    /// The scheme of the data
    pub scheme: Scheme,
    /// The description of the data
    pub description: String,
    /// The type of the data
    #[serde(rename = "type")]
    pub type_: SourceType,
    /// The extension to use when requesting a tile
    pub extension: String,
    /// The encoding of the data
    pub encoding: Encoding,
    /// List of faces that have data
    pub faces: Vec<Face>,
    /// WM Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
    pub bounds: WMBounds,
    /// S2 Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
    pub facesbounds: FaceBounds,
    /// minzoom at which to request tiles. [default=0]
    pub minzoom: u8,
    /// maxzoom at which to request tiles. [default=27]
    pub maxzoom: u8,
    /// The center of the data
    pub center: Center,
    /// { ['human readable string']: 'href' }
    pub attribution: Attribution,
    /// Track layer metadata
    pub layers: LayersMetaData,
    /// Track tile stats for each face and total overall
    pub tilestats: TileStatsMetadata,
    /// Old spec, track basic layer metadata
    pub vector_layers: Vec<VectorLayer>,
}
impl Default for Metadata {
    fn default() -> Self {
        Self {
            s2tilejson: "1.0.0".into(),
            version: "1.0.0".into(),
            name: "default".into(),
            scheme: Scheme::default(),
            description: "Built with s2maps-cli".into(),
            type_: SourceType::default(),
            extension: "pbf".into(),
            encoding: Encoding::default(),
            faces: Vec::new(),
            bounds: WMBounds::default(),
            facesbounds: FaceBounds::default(),
            minzoom: 0,
            maxzoom: 27,
            center: Center::default(),
            attribution: BTreeMap::new(),
            layers: LayersMetaData::default(),
            tilestats: TileStatsMetadata::default(),
            vector_layers: Vec::new(),
        }
    }
}

/// Builder for the metadata
#[derive(Debug, Clone)]
pub struct MetadataBuilder {
    lon_lat_bounds: LonLatBounds,
    faces: BTreeSet<Face>,
    metadata: Metadata,
}
impl Default for MetadataBuilder {
    fn default() -> Self {
        MetadataBuilder {
            lon_lat_bounds: BBox { left: f64::INFINITY, bottom: f64::INFINITY, right: -f64::INFINITY, top: -f64::INFINITY },
            faces: BTreeSet::new(),
            metadata: Metadata { minzoom: 30, maxzoom: 0, ..Metadata::default() },
        }
    }
}
impl MetadataBuilder {
    /// Commit the metadata and take ownership
    pub fn commit(&mut self) -> Metadata {
        // set the center
        self.update_center();
        // set the faces
        for face in &self.faces {
            self.metadata.faces.push(*face);
        }
        // return the result
        self.metadata.to_owned()
    }

    /// Set the name
    pub fn set_name(&mut self, name: String) {
        self.metadata.name = name;
    }

    /// Set the scheme of the data. [default=fzxy]
    pub fn set_scheme(&mut self, scheme: Scheme) {
        self.metadata.scheme = scheme;
    }

    /// Set the extension of the data. [default=pbf]
    pub fn set_extension(&mut self, extension: String) {
        self.metadata.extension = extension;
    }

    /// Set the type of the data. [default=vector]
    pub fn set_type(&mut self, type_: SourceType) {
        self.metadata.type_ = type_;
    }

    /// Set the version of the data
    pub fn set_version(&mut self, version: String) {
        self.metadata.version = version;
    }

    /// Set the description of the data
    pub fn set_description(&mut self, description: String) {
        self.metadata.description = description;
    }

    /// Set the encoding of the data. [default=none]
    pub fn set_encoding(&mut self, encoding: Encoding) {
        self.metadata.encoding = encoding;
    }

    /// add an attribution
    pub fn add_attribution(&mut self, display_name: &str, href: &str) {
        self.metadata.attribution.insert(display_name.into(), href.into());
    }

    /// Add the layer metadata
    pub fn add_layer(&mut self, name: &str, layer: &LayerMetaData) {
        // Only insert if the key does not exist
        if self.metadata.layers.entry(name.into()).or_insert(layer.clone()).eq(&layer) {
            // Also add to vector_layers only if the key was not present and the insert was successful
            self.metadata.vector_layers.push(VectorLayer {
                id: name.into(),  // No need to clone again; we use the moved value
                description: layer.description.clone(),
                minzoom: Some(layer.minzoom),
                maxzoom: Some(layer.maxzoom),
                fields: BTreeMap::new(),
            });
        }
        // update minzoom and maxzoom
        if layer.minzoom < self.metadata.minzoom { self.metadata.minzoom = layer.minzoom; }
        if layer.maxzoom > self.metadata.maxzoom { self.metadata.maxzoom = layer.maxzoom; }
    }

    /// Add the WM tile metadata
    pub fn add_tile_wm(&mut self, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
        self.metadata.tilestats.total += 1;
        self.faces.insert(Face::Face0);
        self.add_bounds_wm(zoom, x, y);
        self.update_lon_lat_bounds(ll_bounds);
    }

    /// Add the S2 tile metadata
    pub fn add_tile_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
        self.metadata.tilestats.increment(face);
        self.faces.insert(face);
        self.add_bounds_s2(face, zoom, x, y);
        self.update_lon_lat_bounds(ll_bounds);
    }

    /// Update the center now that all tiles have been added
    fn update_center(&mut self) {
        let Metadata { minzoom, maxzoom, .. } = self.metadata;
        let BBox { left, bottom, right, top } = self.lon_lat_bounds;
        self.metadata.center.lon = (left + right) / 2.0;
        self.metadata.center.lat = (bottom + top) / 2.0;
        self.metadata.center.zoom = (minzoom + maxzoom) >> 1;
    }

    /// Add the bounds of the tile for WM data
    fn add_bounds_wm(&mut self, zoom: u8, x: u32, y: u32) {
        let x = x as u64;
        let y = y as u64;
        let bbox = self.metadata.bounds.entry(zoom).or_insert(BBox{ 
            left: u64::MAX, bottom: u64::MAX, right: 0, top: 0
        });
        
        bbox.left = bbox.left.min(x);
        bbox.bottom = bbox.bottom.min(y);
        bbox.right = bbox.right.max(x);
        bbox.top = bbox.top.max(y);
    }

    /// Add the bounds of the tile for S2 data
    fn add_bounds_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32) {
        let x = x as u64;
        let y = y as u64;
        let bbox = self.metadata.facesbounds.get_mut(face).entry(zoom).or_insert(BBox{ 
            left: u64::MAX, bottom: u64::MAX, right: 0, top: 0
        });
        
        bbox.left = bbox.left.min(x);
        bbox.bottom = bbox.bottom.min(y);
        bbox.right = bbox.right.max(x);
        bbox.top = bbox.top.max(y);
    }

    /// Update the lon-lat bounds so eventually we can find the center point of the data
    fn update_lon_lat_bounds(&mut self, ll_bounds: &LonLatBounds) {
        self.lon_lat_bounds.left = ll_bounds.left.min(self.lon_lat_bounds.left);
        self.lon_lat_bounds.bottom = ll_bounds.bottom.min(self.lon_lat_bounds.bottom);
        self.lon_lat_bounds.right = ll_bounds.right.max(self.lon_lat_bounds.right);
        self.lon_lat_bounds.top = ll_bounds.top.max(self.lon_lat_bounds.top);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut meta_builder = MetadataBuilder::default();


        // on initial use be sure to update basic metadata:
        meta_builder.set_name("OSM".into());
        meta_builder.set_description("A free editable map of the whole world.".into());
        meta_builder.set_version("1.0.0".into());
        meta_builder.set_scheme("fzxy".into()); // 'fzxy' | 'tfzxy' | 'xyz' | 'txyz' | 'tms'
        meta_builder.set_type("vector".into()); // 'vector' | 'json' | 'raster' | 'raster-dem' | 'sensor' | 'markers'
        meta_builder.set_encoding("none".into()); // 'gz' | 'br' | 'none'
        meta_builder.set_extension("pbf".into());
        meta_builder.add_attribution("OpenStreetMap", "https://www.openstreetmap.org/copyright/");

        // Vector Specific: add layers based on how you want to parse data from a source:
        let shape_str = r#"
        {
            "class": "string",
            "offset": "f64",
            "info": {
                "name": "string",
                "value": "i64"
            }
        }
        "#;
        let shape: Shape = serde_json::from_str(shape_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
        let layer = LayerMetaData {
            minzoom: 0,
            maxzoom: 13,
            description: Some("water_lines".into()),
            draw_types: Vec::from(&[DrawType::Lines]),
            shape: shape.clone(),
            m_shape: None,
        };
        meta_builder.add_layer("water_lines", &layer);

        // as you build tiles, add the tiles metadata:
        // WM:
        meta_builder.add_tile_wm(0, 0, 0, &LonLatBounds{ left: -60.0, bottom: -20.0, right: 5.0, top: 60.0 });
        // S2:
        meta_builder.add_tile_s2(Face::Face1, 5, 22, 37, &LonLatBounds { left: -120.0, bottom: -7.0, right: 44.0, top: 72.0 });

        // finally to get the resulting metadata:
        let resulting_metadata: Metadata = meta_builder.commit();

        assert_eq!(resulting_metadata, Metadata {
            name: "OSM".into(),
            description: "A free editable map of the whole world.".into(),
            version: "1.0.0".into(),
            scheme: "fzxy".into(),
            type_: "vector".into(),
            encoding: "none".into(),
            extension: "pbf".into(),
            attribution: BTreeMap::from([
                ("OpenStreetMap".into(), "https://www.openstreetmap.org/copyright/".into()),
            ]),
            bounds: BTreeMap::from([
                (0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 }),
            ]),
            faces: Vec::from(&[Face::Face0, Face::Face1]),
            facesbounds: FaceBounds {
                face0: BTreeMap::new(),
                face1: BTreeMap::from([
                    (5, TileBounds { left: 22, bottom: 37, right: 22, top: 37 }),
                ]),
                face2: BTreeMap::new(),
                face3: BTreeMap::new(),
                face4: BTreeMap::new(),
                face5: BTreeMap::new(),
            },
            minzoom: 0,
            maxzoom: 13,
            center: Center { lon: -38.0, lat: 26.0, zoom: 6 },
            tilestats: TileStatsMetadata {
                total: 2,
                total_0: 0,
                total_1: 1,
                total_2: 0,
                total_3: 0,
                total_4: 0,
                total_5: 0,
            },
            layers: BTreeMap::from([("water_lines".into(), LayerMetaData{
                description: Some("water_lines".into()),
                minzoom: 0,
                maxzoom: 13,
                draw_types: Vec::from(&[DrawType::Lines]),
                shape: BTreeMap::from([
                    ("class".into(), ShapeType::Primitive(PrimitiveShape::String)),
                    ("offset".into(), ShapeType::Primitive(PrimitiveShape::F64)),
                    ("info".into(), ShapeType::Nested(BTreeMap::from([
                        ("name".into(), ShapeType::Primitive(PrimitiveShape::String)),
                        ("value".into(), ShapeType::Primitive(PrimitiveShape::I64)),
                    ]))),
                ]),
                m_shape: None,
            })]),
            s2tilejson: "1.0.0".into(),
            vector_layers: Vec::from([VectorLayer { id: "water_lines".into(), description: Some("water_lines".into()), minzoom: Some(0), maxzoom: Some(13), fields: BTreeMap::new() }]),
        });
    }
}