use std::collections::HashMap;

use avian3d::math::PI;
use bevy::prelude::*;

use crate::tb_entities::NamedEntity;

#[derive(Resource)]
enum GatesState {
    Init,
    GateOpen1,
}

pub fn plugin(app: &mut App) {
    app.insert_resource(GatesState::Init);
    app.add_systems(Update, update);
}

fn update(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut state: ResMut<GatesState>,
    mut names_entities: Query<(&NamedEntity, &mut Transform)>,
) {
    if keyboard.just_pressed(KeyCode::Digit1) {
        if matches!(*state, GatesState::Init) {
            *state = GatesState::GateOpen1;

            let fences: HashMap<_, _> = vec![
                ("fence_01", Quat::from_rotation_y(PI / -2.)),
                ("fence_02", Quat::from_rotation_y(PI / 2.)),
            ]
            .into_iter()
            .collect();

            for (named_entity, mut transform) in names_entities.iter_mut() {
                if let Some(fence) = fences.get(named_entity.name.as_str()) {
                    transform.rotate(*fence);
                }
            }
        }
    }
}
