use std::sync::{Arc, Mutex};
use eframe::{Frame, Storage};
use egui::{Context, Event, MouseWheelUnit, Sense, Vec2};
use tracing::debug;
use crate::map::{Map};
use crate::map::osm::OSMBaselayer;
use crate::map::tiles::{LayerManager, LayerSource};

pub struct App {
    map: Arc<Mutex<Map>>
}

impl App {
    pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
        let mut layer_manager = LayerManager::default();
        layer_manager.layers.insert(0, OSMBaselayer::SOURCE_ID);

        Self {
            map: Arc::new(Mutex::new(Map::new(layer_manager, cc).unwrap())),
        }
    }
}

impl eframe::App for App {
    fn update(&mut self, ctx: &Context, frame: &mut Frame) {
        egui::SidePanel::left("sidebar")
            .resizable(false)
            .show(ctx, |ui| {
                ui.heading("wxbox");
            });

        egui::CentralPanel::default()
            .show(ctx, |ui| {
                {
                    let map = self.map.clone();
                    map.lock().unwrap().custom_painting(&ctx, ui);
                }
            });
    }

    fn on_exit(&mut self, gl: Option<&glow::Context>) {
        if let Some(gl) = gl {
            self.map.lock().unwrap().render.lock().unwrap().destroy(gl);
        }
    }
}