use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;
use camera::CameraPlugin;
use logging::log_positions;
use player::PlayerPlugin;
use goal::{GoalBundle, check_goal};
use level_structure::WallBundle;

mod camera;
mod logging;
mod player;
mod goal;
mod level_structure;

pub const GRID_SIZE: i32 = 16;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
        .add_plugins(LdtkPlugin)
        .add_plugins(PlayerPlugin)
        .insert_resource(LevelSelection::index(0))
        .register_ldtk_entity::<GoalBundle>("Goal")
        .register_ldtk_int_cell::<WallBundle>(1)
        .add_systems(Startup, setup)
        .add_plugins(CameraPlugin)
        .add_systems(Update, (translate_grid_coords_entities, check_goal))
        .add_systems(Update, log_positions)
        .run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(LdtkWorldBundle {
        ldtk_handle: asset_server.load("shocked-miguel.ldtk"),
        ..Default::default()
    });
}

fn translate_grid_coords_entities(
    mut grid_coords_entities: Query<(&mut Transform, &GridCoords), Changed<GridCoords>>,
) {
    for (mut transform, grid_coords) in grid_coords_entities.iter_mut() {
        transform.translation =
            bevy_ecs_ldtk::utils::grid_coords_to_translation(*grid_coords, IVec2::splat(GRID_SIZE))
                .extend(transform.translation.z);
    }
}
