use crate::coords::Mapper;
use crate::render::Render;
use femtovg::renderer::OpenGl;
use femtovg::{Canvas, Paint};
use geo_types::LineString;
use geojson::GeoJson;

pub struct MapRender;

impl MapRender {
    pub fn test(geojson: &GeoJson, canvas: &mut Canvas<OpenGl>, render: &Render) {
        let paint = Paint::color(femtovg::Color::rgb(255, 255, 255));

        if let GeoJson::FeatureCollection(ref feature_collection) = geojson {
            for feature in &feature_collection.features {
                feature
                    .geometry
                    .as_ref()
                    .iter()
                    .for_each(|geometry| match geometry.value {
                        geojson::Value::Polygon(ref polygon) => {
                            let mut path = femtovg::Path::new();
                            let polygon = &polygon[0];
                            for (i, point) in polygon.iter().enumerate() {
                                let _point = (point[0], point[1]);
                                if render.point_in_bound(_point) {
                                    let (x, y) = render.map(_point).unwrap();
                                    if i == 0 {
                                        path.move_to(x, y);
                                    } else {
                                        path.line_to(x, y);
                                    }
                                }
                            }
                        }
                        geojson::Value::MultiPolygon(ref multi_polygon) => {
                            let mut path = femtovg::Path::new();
                            for polygon in multi_polygon {
                                let out_ring = &polygon[0];
                                let out_ring_line: LineString = out_ring
                                    .iter()
                                    .map(|x| (x[0], x[1]))
                                    .collect::<Vec<_>>()
                                    .into();
                                let out_ring = render.ring_map(&out_ring_line).unwrap();

                                for (i, point) in out_ring.points().enumerate() {
                                    let (x, y) = (point.x(), point.y());
                                    if i == 0 {
                                        path.move_to(x, y);
                                    } else {
                                        path.line_to(x, y);
                                    }
                                }
                            }
                            canvas.stroke_path(&mut path, &paint);
                        }
                        _ => println!("Unknown geometry type: {:?}", geometry.value),
                    });
            }
        }
    }
}
