use crate::components::*;
use bevy::prelude::*;

pub fn spawn_customers(
    mut commands: Commands,
    mut spawner: ResMut<CustomerSpawner>,
    mut queue: ResMut<CounterQueue>,
    time: Res<Time>,
    asset_server: Res<AssetServer>,
) {
    spawner.timer.tick(time.delta());

    // Guard clause
    if !spawner.timer.just_finished() {
        return;
    }

    // check positions
    let available_slot = queue.occupied.iter().position(|&occupied| !occupied);

    let Some(slot_index) = available_slot else {
        println!("FULL");
        return;
    };

    // Take first location
    let target_position = queue.positions[slot_index];
    queue.occupied[slot_index] = true;

    commands.spawn((
        SceneRoot(asset_server.load("models/customer.glb#Scene0")),
        Transform::from_xyz(20.0, 1.5, 0.0).with_scale(Vec3::splat(0.5)),
        Unit {
            move_speed: 5.0,
            height_offset: 1.5,
        },
        Customer {
            order: Item::Burger,
            served: false,
            range: 4.0,
        },
        MoveTarget {
            position: target_position,
        },
        QueueSlot(slot_index),
        children![(
            SceneRoot(asset_server.load("models/burger.glb#Scene0")),
            Transform::from_xyz(0.0, 7.1, 0.0).with_scale(Vec3::splat(0.9)),
            Visibility::Hidden,
            CustomerBurgerIndicator,
        )],
    ));
}

pub fn despawn_customers(
    mut commands: Commands,
    mut queue: ResMut<CounterQueue>,
    customers: Query<(Entity, &Transform, &Customer, &QueueSlot)>,
) {
    for (entity, transform, customer, slot) in customers.iter() {
        if customer.served && transform.translation.x > 25.0 {
            // Customer reached border
            queue.occupied[slot.0] = false;

            commands.entity(entity).despawn();

            println!("CUSTOMER DELETED!");
        }
    }
}

pub fn update_customer_indicators(
    customers: Query<(&Customer, &Children)>,
    mut burgers: Query<&mut Visibility, With<CustomerBurgerIndicator>>,
) {
    for (customer, children) in customers.iter() {
        for child in children.iter() {
            if let Ok(mut visibility) = burgers.get_mut(child) {
                *visibility = if customer.served {
                    Visibility::Visible
                } else {
                    Visibility::Hidden
                };
            }
        }
    }
}
