mod imp;
use crate::{coords::Range, render::Render};
use femtovg::{renderer::OpenGl, Canvas, Color, Paint, Path};
use glib::subclass::types::ObjectSubclassIsExt;

glib::wrapper! {
    pub struct ExteriorWidget(ObjectSubclass<imp::ExteriorWidget>);
}

impl Default for ExteriorWidget {
    fn default() -> Self {
        Self::new()
    }
}

impl ExteriorWidget {
    pub fn new() -> Self {
        let this: Self = glib::Object::new();
        this
    }

    pub fn draw(&self, canvas: &mut Canvas<OpenGl>, render: &Render) {
        let padding = render.imp().config.borrow().padding;
        let (w, h) = render.window_size();
        let (w, h) = (w as f32, h as f32);
        let origins = [
            (0.0, 0.0),
            (w - padding[1], 0.0),
            (0.0, h - padding[2]),
            (0.0, 0.0),
        ];
        let whs = [
            (w, padding[0]),
            (padding[1], h),
            (w, padding[2]),
            (padding[3], h),
        ];

        let painter = Paint::color(Color::rgb(0, 0, 0));

        for edge in 0..4 {
            let mut path = Path::new();
            let (ox, oy) = origins[edge];
            let (w, h) = whs[edge];
            path.rect(ox, oy, w, h);
            canvas.fill_path(&path, &painter);
        }

        let (lon_range, lat_range) = render.render_range();
        let (lon_range, lat_range): (Range, Range) = (lon_range.into(), lat_range.into());

        let lon_keypoints = lon_range.key_points(10);
        let lat_keypoints = lat_range.key_points(5);
        let mut paint = Paint::color(Color::white()); // 黑色字体
        paint.set_font_size(25.0);

        for lon in lon_keypoints.iter() {
            let (x, _) = render.map((*lon, lat_range.0)).unwrap();

            let text = format!("{:.2}", lon);
            let metrics = canvas
                .measure_text(x, 0.0, text.as_str(), &paint)
                .expect("Cannot measure text");

            let text_x = x - metrics.width() / 2.0;
            let text_y = h - metrics.height() / 2.0;

            canvas
                .fill_text(text_x, text_y, text.as_str(), &paint)
                .expect("Cannot draw text");
        }

        for lat in lat_keypoints.iter() {
            let (_, y) = render.map((lon_range.0, *lat)).unwrap();

            let text = format!("{:.2}", lat);
            let metrics = canvas
                .measure_text(0.0, y, text.as_str(), &paint)
                .expect("Cannot measure text");

            let text_x = 0.0;
            let text_y = y - metrics.height() / 2.0;

            canvas
                .fill_text(text_x, text_y, text.as_str(), &paint)
                .expect("Cannot draw text");
        }
    }
}
