mod alien;
mod camera;
mod cash;
mod gates;
mod heads_ui;
mod player;
mod tb_entities;

use avian3d::PhysicsPlugins;
use avian3d::prelude::*;
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::prelude::*;
use bevy::render::view::ColorGrading;
use bevy_dolly::prelude::*;
use bevy_tnua::prelude::TnuaControllerPlugin;
use bevy_tnua_avian3d::TnuaAvian3dPlugin;
use bevy_trenchbroom::prelude::*;
use camera::GameCameraRig;

#[derive(Resource, Reflect, Debug)]
#[reflect(Resource)]
struct DebugVisuals {
    pub unlit: bool,
    pub tonemapping: Tonemapping,
    pub exposure: f32,
    pub shadows: bool,
    pub cam_follow: bool,
}

#[derive(Component, Debug)]
pub struct MainCamera;

fn main() {
    let mut app = App::new();

    app.register_type::<DebugVisuals>();
    app.insert_resource(DebugVisuals {
        unlit: false,
        tonemapping: Tonemapping::None,
        exposure: 1.,
        shadows: true,
        cam_follow: true,
    });

    app.add_plugins(DefaultPlugins.set(ImagePlugin {
        default_sampler: repeating_image_sampler(false),
    }));

    // app.add_plugins(bevy::pbr::wireframe::WireframePlugin)
    //     .insert_resource(bevy::pbr::wireframe::WireframeConfig {
    //         global: true,
    //         default_color: bevy::color::palettes::css::WHITE.into(),
    //     });

    app.add_plugins(PhysicsPlugins::default());
    // app.add_plugins(PhysicsDebugPlugin::default());
    app.add_plugins((
        TnuaControllerPlugin::new(FixedUpdate),
        TnuaAvian3dPlugin::new(FixedUpdate),
    ));

    app.add_systems(Update, Dolly::<MainCamera>::update_active);

    app.add_plugins(alien::plugin);
    app.add_plugins(cash::plugin);
    app.add_plugins(player::plugin);
    app.add_plugins(heads_ui::plugin);
    app.add_plugins(gates::plugin);

    app.insert_resource(AmbientLight {
        color: Color::WHITE,
        brightness: 400.,
    });
    app.add_plugins(bevy_inspector_egui::quick::WorldInspectorPlugin::default());

    app.add_plugins(TrenchBroomPlugin(TrenchBroomConfig::new("hedz")));

    app.add_systems(Startup, (setup_cam, write_trenchbroom_config, music));
    app.add_systems(PostStartup, setup_scene);
    app.add_systems(
        Update,
        (set_materials_unlit, set_tonemapping, set_shadows, spawn_box),
    );

    app.run();
}

fn setup_cam(mut commands: Commands) {
    commands.spawn((
        Camera3d::default(),
        MainCamera,
        Rig::builder()
            .with(GameCameraRig::new_with_arm(Vec3::new(0., 5., 14.)))
            .build(),
    ));
}

fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(SceneRoot(asset_server.load("maps/map1.map#Scene")));

    commands.spawn((
        DirectionalLight {
            illuminance: light_consts::lux::OVERCAST_DAY,
            shadows_enabled: true,
            ..default()
        },
        Transform {
            translation: Vec3::new(0.0, 2.0, 0.0),
            rotation: Quat::from_rotation_x(-1.7),
            ..default()
        },
    ));
}

fn spawn_box(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    keys: Res<ButtonInput<KeyCode>>,
) {
    if keys.just_pressed(KeyCode::Enter) {
        commands.spawn((
            RigidBody::Dynamic,
            Collider::cuboid(5.0, 5.0, 5.0),
            AngularVelocity(Vec3::new(2.5, 3.5, 1.5)),
            Mesh3d(meshes.add(Cuboid::from_length(5.0))),
            MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
            Transform::from_xyz(0.0, 50.0, 0.0),
        ));
    }
}

fn music(asset_server: Res<AssetServer>, mut commands: Commands) {
    commands.spawn(AudioPlayer::new(asset_server.load("sfx/music/02.ogg")));
}

fn write_trenchbroom_config(server: Res<TrenchBroomServer>) {
    server.config.write_folder("trenchbroom/hedz").unwrap()
}

fn set_tonemapping(
    mut cams: Query<(&mut Tonemapping, &mut ColorGrading), With<Camera>>,
    visuals: Res<DebugVisuals>,
) {
    for (mut tm, mut color) in cams.iter_mut() {
        *tm = visuals.tonemapping;
        color.global.exposure = visuals.exposure;
    }
}

fn set_materials_unlit(
    mut materials: ResMut<Assets<StandardMaterial>>,
    visuals: Res<DebugVisuals>,
) {
    if !materials.is_changed() {
        return;
    }

    for (_, material) in materials.iter_mut() {
        material.unlit = visuals.unlit;
    }
}

fn set_shadows(mut lights: Query<&mut DirectionalLight>, visuals: Res<DebugVisuals>) {
    for mut l in lights.iter_mut() {
        l.shadows_enabled = visuals.shadows;
    }
}
