use super::passes;
use crate::render::wgpu::rendergraph::render_graph_get_pass_mut;

impl super::WgpuRenderer {
    /// Drains the egui frame output stashed on `world.resources.egui` and hands
    /// it to the [`EguiPass`](passes::EguiPass) node: uploads texture deltas and
    /// sets the paint jobs and screen descriptor the pass renders this frame.
    /// Called early in [`render_frame`](super::WgpuRenderer::render_frame),
    /// before the graph executes.
    pub(super) fn prepare_egui_pass(&mut self, world: &mut crate::ecs::world::World) {
        let Some((output, primitives)) = world.resources.egui.frame_output.take() else {
            return;
        };

        let screen_descriptor = egui_wgpu::ScreenDescriptor {
            size_in_pixels: [self.surface_config.width, self.surface_config.height],
            pixels_per_point: output.pixels_per_point,
        };

        if let Some(egui_pass) = render_graph_get_pass_mut(&mut self.graph, "egui_pass")
            && let Some(egui_pass) =
                (egui_pass as &mut dyn std::any::Any).downcast_mut::<passes::EguiPass>()
        {
            egui_pass.update_textures(&self.device, &self.queue, &output.textures_delta);
            egui_pass.set_screen_descriptor(screen_descriptor);
            egui_pass.set_paint_jobs(primitives);
        }
    }
}
