//! Forces viewport tile re-renders for editor state the engine's dirty
//! tracking cannot see. Camera tiles default to dirty driven updates, but
//! selection changes only move the gizmo and visibility flips are not
//! dirty signaled at all, so the selection outline and show or hide
//! toggles would otherwise leave stale pixels in the cached viewport.

use crate::ecs::EditorWorld;
use nightshade::prelude::*;
use std::hash::{Hash, Hasher};

pub fn update(editor_world: &mut EditorWorld, world: &mut World) {
    let mut visibility_hash: u64 = 0;
    world
        .core
        .query()
        .with(nightshade::ecs::world::VISIBILITY)
        .iter(|entity, table, index| {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            (entity.id, table.visibility[index].visible).hash(&mut hasher);
            visibility_hash ^= hasher.finish();
        });

    let primary_selection = editor_world.resources.ui.selected_entity;
    let selection_count = editor_world.resources.ui.selected_entities.len();

    let repaint = &mut editor_world.resources.repaint;
    if repaint.last_primary_selection == primary_selection
        && repaint.last_selection_count == selection_count
        && repaint.last_visibility_hash == visibility_hash
    {
        return;
    }
    repaint.last_primary_selection = primary_selection;
    repaint.last_selection_count = selection_count;
    repaint.last_visibility_hash = visibility_hash;

    let cameras: Vec<Entity> = world
        .resources
        .window
        .camera_tile_rects
        .keys()
        .copied()
        .collect();
    for camera in cameras {
        world.resources.window.force_render_cameras.insert(camera);
    }
}
