/*
Trouble in Terror Town: Community Edition
Copyright (C) 2024 Mikolaj Wojciech Gorski

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License 3.0 as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License 3.0 for more details.

You should have received a copy of the GNU General Public License 3.0
along with this program.  If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
*/

#![allow(clippy::type_complexity)]

#[cfg(debug_assertions)]
use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
use bevy::prelude::*;
use bevy_editor_pls::prelude::*;
use bevy_xpbd_3d::prelude::*;

mod weapon_framework;
mod player_utils;

use player_utils::character_controller::*;
use player_utils::input_processor::*;
use player_utils::player_look::*;

#[derive(Resource, Default, Debug)]
struct IsMapSpawned(bool);

pub struct GamePlugin;

impl Plugin for GamePlugin {
    fn build(&self, app: &mut App) {
        app.add_plugins((
            PhysicsPlugins::default(),
            InputProcessorPlugin,
            CharacterControllerPlugin,
            PlayerLookPlugin,
        ))
        .add_systems(Startup, setup)
        .add_systems(Update, spawn_map);

        #[cfg(debug_assertions)]
        {
            app.add_plugins((
                FrameTimeDiagnosticsPlugin,
                EditorPlugin::default(),
                LogDiagnosticsPlugin::default(),
            ));
        }

        app.world.init_resource::<IsMapSpawned>();
    }
}

/// set up a simple 3D scene
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    // light
    commands.spawn(PointLightBundle {
        point_light: PointLight {
            shadows_enabled: true,
            ..default()
        },
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..default()
    });
    //player
    spawn_player(
        commands,
        meshes,
        materials,
        0.5,
        CharacterControllerBundle::new(Collider::capsule(1.0, 0.5), CharacterController::default()),
    );
}

fn spawn_map(
    asset_server: Res<AssetServer>,
    mut is_map_spawned: ResMut<IsMapSpawned>,
    mut commands: Commands,
) {
    if is_map_spawned.0 {
        return;
    }

    let scene = asset_server.load("test_map.gltf#Scene0");

    commands.spawn((
        SceneBundle {
            scene: scene.clone(),
            transform: Transform::from_xyz(0.0, 0.0, 0.0),
            ..default()
        },
        AsyncSceneCollider::new(Some(ComputedCollider::TriMesh)),
        RigidBody::Static,
    ));

    println!("map spawned!");

    is_map_spawned.0 = true
}
