use femtovg::Paint;
use num_traits::{Num, NumOps};
use std::path::Path;

use crate::{
    data::{DataLoader, Radar2d},
    render::Layer
};

use super::{
    color_mapper::ColorMapper,
    grid_field_renderer::{GridFieldRenderer, GridLayerImpl},
};

impl Layer {
    pub fn grid_render_layer<T, CMAP>(data: Radar2d<T>, color_map: CMAP) -> Self
    where
        T: std::fmt::Debug + Num + NumOps + PartialOrd + Copy + Clone + 'static,
        CMAP: ColorMapper<T> + 'static,
    {
        Self::new(
            true,
            |s, c, render, _| {
                if let Some(target) = s.render_target() {
                    if let Ok(_) = c.image_size(target.target) {
                        let (x, y) = target.size(render);
                        let (ox, oy) = target.origin(render);
                        let painter = Paint::image(target.target, ox, oy, x, y, 0.0, 1.0);
                        let mut path = femtovg::Path::new();
                        path.rect(ox, oy, x, y);
                        c.fill_path(&path, &painter);
                    }
                } else {
                    if let Some(renderer) = s.get_imp().as_ref() {
                        let img = renderer.draw(c, render).unwrap();
                        if let Ok(_) = c.image_size(img.target) {
                            let (x, y) = img.size(render);
                            let (ox, oy) = img.origin(render);
                            println!("{} {} {} {}", x, y, ox, oy);
                            let painter = Paint::image(img.target, ox, oy, x, y, 0.0, 1.0);
                            let mut path = femtovg::Path::new();
                            path.rect(ox, oy, x, y);
                            s.set_render_target(img);
                            c.fill_path(&path, &painter);
                            c.flush();
                        }
                    }
                }
            },
            Some(GridLayerImpl::new(GridFieldRenderer::new(color_map), data)),
        )
    }

    pub fn grid_render_layer_with_path<T, CMAP, LOADER>(
        path: impl AsRef<Path>,
        loader: LOADER,
        color_map: CMAP,
    ) -> Self
    where
        T: Num + NumOps + PartialOrd + Copy + Clone + 'static + std::fmt::Debug,
        CMAP: ColorMapper<T> + 'static,
        LOADER: DataLoader<T, Radar2d<T>>,
    {
        let data = loader.load(path).unwrap();
        self::Layer::grid_render_layer(data, color_map)
    }
}
