use crate::mosaic::WidgetContext;
use nightshade::prelude::serde::{Deserialize, Serialize};
use nightshade::prelude::*;

use crate::app_context::AppContext;
use crate::messages::EditorMessage;

#[derive(Clone, Serialize, Deserialize)]
#[serde(crate = "nightshade::prelude::serde")]
#[cfg_attr(target_arch = "wasm32", derive(Default))]
pub struct WebWidget {
    #[cfg(not(target_arch = "wasm32"))]
    pub url: String,
    #[cfg(not(target_arch = "wasm32"))]
    pub id: String,
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for WebWidget {
    fn default() -> Self {
        Self {
            url: "https://matthewberger.dev/nightshade".to_string(),
            id: nightshade::prelude::uuid::Uuid::new_v4().to_string(),
        }
    }
}

impl WebWidget {
    pub(crate) fn render(
        &mut self,
        ui: &mut egui::Ui,
        context: &mut WidgetContext<AppContext, EditorMessage>,
    ) {
        let rect = ui.available_rect_before_wrap();

        ui.painter()
            .rect_filled(rect, 0.0, ui.style().visuals.panel_fill);

        #[cfg(target_arch = "wasm32")]
        {
            let _ = context;
            ui.centered_and_justified(|ui| {
                ui.label("Web widget is unavailable on wasm");
            });
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            context
                .app
                .ui
                .web_widget_rects
                .push((self.id.clone(), self.url.clone(), rect));
        }
    }
}
