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

pub fn fryer_cook(
    mut player: Query<(&mut Player, &Transform)>,
    fryer: Query<(&Fryer, &Transform)>,
    time: Res<Time>,
) {
    let Ok((mut player_data, player_transform)) = player.single_mut() else {
        return;
    };
    if player_data.holding == Item::Burger {
        return;
    }
    for (fryer, fryer_transform) in fryer.iter() {
        let distance = player_transform.translation - fryer_transform.translation;
        if distance.length() < fryer.range {
            player_data.progress += fryer.speed * time.delta_secs();

            if player_data.progress > 100.0 {
                player_data.holding = Item::Burger;
                println!("YOU HAVE BURGER!!");
            }
        } else {
            player_data.progress = 0.0;
        }
    }
}

pub fn customer_serve(
    mut customer: Query<(&mut Customer, &mut MoveTarget, &Transform)>,
    mut player: Query<(&mut Player, &Transform)>,
) {
    let Ok((mut player_data, player_transform)) = player.single_mut() else {
        return;
    };
    if player_data.holding == Item::None {
        return;
    }
    for (mut customer_data, mut customer_target, customer_transform) in customer.iter_mut() {
        if customer_data.served {
            continue;
        }
        if player_data.holding != customer_data.order {
            continue;
        }

        let distance = player_transform.translation - customer_transform.translation;
        if distance.length() < customer_data.range {
            player_data.holding = Item::None;
            customer_data.served = true;
            customer_target.position = Vec3::new(100.0, 0.0, 0.0);
        }
    }
}
