use bevy::log::LogPlugin;
use bevy::prelude::*;
use bevy::state::app::StatesPlugin;
use bevy_editor_pls::prelude::*;
use blenvy::{BlenvyPlugin, BlueprintInfo, GameWorldTag, HideUntilReady, SpawnBlueprint};
use clap::Parser;
use lightyear::prelude::client::ClientPlugins;
use lightyear::prelude::server::ServerPlugins;
use std::f32::consts::PI;

pub mod protocol;
pub mod shared_net;

#[derive(Component, PartialEq, Eq, Default, Reflect)]
#[reflect(Component)]
pub struct Player;

lazy_static::lazy_static! {
    pub static ref CONFIG: Cli = {
        Cli::parse()
    };
}

pub struct ClientOrServerPlugin;
impl Plugin for ClientOrServerPlugin {
    fn build(&self, app: &mut App) {
        if CONFIG.client {
            app.add_plugins(DefaultPlugins)
                .add_plugins(ClientPlugins::new(shared_net::client_config()));
        }
        if CONFIG.server {
            app.add_plugins((MinimalPlugins, StatesPlugin, LogPlugin::default()))
                .add_plugins(ServerPlugins::new(shared_net::server_config()));
        }
    }
}

#[derive(Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
    /// Start as a client.
    #[arg(short, long)]
    client: bool,
    /// Start as a server.
    #[arg(short, long)]
    server: bool,
}
fn main() {
    App::new()
        .register_type::<Player>()
        .insert_resource(Msaa::Sample4)
        .insert_resource(AmbientLight {
            brightness: 200.0,
            ..default()
        })
        .add_plugins(ClientOrServerPlugin)
        .add_plugins(protocol::ProtocolPlugin)
        .add_plugins(EditorPlugin::default())
        .add_plugins(BlenvyPlugin::default())
        .add_systems(Startup, setup)
        .run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // commands.spawn(PointLightBundle {
    //     transform: Transform::from_translation(Vec3::Y * 30.),
    //     point_light: PointLight {
    //         intensity: 20_000_000.0,
    //         shadows_enabled: true,
    //         range: 100.,
    //         ..default()
    //     },
    //     ..default()
    // });

    commands.spawn((
        DirectionalLightBundle {
            transform: Transform::from_translation(Vec3::Y * 10.).with_rotation(Quat::from_euler(
                EulerRot::XYZ,
                3. * PI / 2.,
                0.,
                0.,
            )),
            directional_light: DirectionalLight {
                shadows_enabled: true,
                ..default()
            },
            ..default()
        },
        Name::new("Sun"),
    ));

    // commands.spawn(SceneBundle {
    //     scene: asset_server.load("hotel.glb#Scene0"),
    //     ..Default::default()
    // });
    commands.spawn((
        BlueprintInfo::from_path("levels/World.glb"),
        SpawnBlueprint,
        HideUntilReady,
        GameWorldTag,
    ));
}
