extern crate env_logger;
extern crate imgui;
extern crate imgui_wgpu;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
extern crate tobj;
extern crate toml;
extern crate winit_24;

use std::collections::HashMap;
use std::f32::consts::PI;
use std::fs;
use std::sync::{Arc, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};

use cgmath::{
    Decomposed, Deg, Euler, InnerSpace, Point3, Quaternion, Rad, Rotation3, SquareMatrix,
};
use futures::executor::block_on;
use futures::task::LocalSpawn;
use futures::FutureExt;
use gilrs::Event as GilEvent;
use gilrs::{Gamepad, Gilrs};
use imgui::FontSource;
use imgui::__core::convert::TryInto;
use imgui::*;
use imgui_wgpu::{Renderer as ImguiRenderer, RendererConfig as ImguiRendererConfig};
use legion::systems::{SyncResources, UnsafeResources};
use legion::*;
use log::LevelFilter;
use rapier3d::counters::Timer;
use rapier3d::dynamics::{
    IntegrationParameters, JointSet, RigidBody, RigidBodyBuilder, RigidBodyHandle, RigidBodySet,
};
use rapier3d::geometry::{BroadPhase, ColliderBuilder, ColliderHandle, ColliderSet, NarrowPhase};
use rapier3d::math;
use rapier3d::math::Point;
use rapier3d::na::{Isometry, Isometry3, Vector, Vector3};
use rapier3d::pipeline::PhysicsPipeline;
use wgpu::{BindGroup, Buffer, TextureView};
use wgpu_subscriber;
use winit_24::event::DeviceEvent::MouseMotion;
use winit_24::event::{ElementState, VirtualKeyCode};
use winit_24::event_loop::EventLoopProxy;
use winit_24::window::Window;
use winit_24::{
    event::{self, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
};

use crate::camera::{Camera, CameraController};
use crate::components::{Collider, ImguiWindow, LoopState, Physics, Position};
use crate::geometry::{load_obj, RawMesh};
use crate::imgui_supp::extended_winit_imgui_support;
use crate::imgui_supp::imgui_support::{ImguiContext, ImguiPlatform};
use crate::owned_event::{OwnedEvent, OwnedEventExtension};
use crate::physics::state::PhysicsState;
use crate::render::system::ImguiPerformanceProfilerLine;
use crate::runtime::state::RuntimeState;
use winit_24::dpi::PhysicalSize;

mod camera;
mod components;
mod geometry;
mod imgui_supp;
mod light;
mod owned_event;
mod physics;
mod render;
mod runtime;

/*

Collision detection
https://nphysics.org/rigid_body_simulations_with_contacts/

Obj file format
http://paulbourke.net/dataformats/obj/

tobj obj loader
https://docs.rs/tobj/2.0.3/tobj/index.html

mesh generator lib, might be useful
https://docs.rs/genmesh/0.6.2/genmesh/

legion ECS
https://github.com/amethyst/legion


ECS
    animation
    config / save loading (sorta!)
    render 3d (good!)
    input/io (yep!)
    collision / physics (yep!)
    entities & behaviours (got the entities!)
    scripting!


Todo:
    Load scene imgui interface w/ toml files
    FPS graph port from voxel raycaster
    better imgui interface with components & systems
    Figure out eventing, GameInput, passing all events, etc.
    + texturing

I need to figure out the way that I want to do 2d graphics in a 3d engine...
I suppose I will need sprites. And those are just 2 polygons which are textured



 */

//log::info!("");

// ImGUI works on more or less an unsafe global state. which is MegaLame
static mut CURRENT_UI: Option<imgui::Ui<'static>> = None;
pub unsafe fn current_ui<'a>() -> Option<&'a imgui::Ui<'a>> {
    CURRENT_UI.as_ref()
}



fn main() {
    let logger = env_logger::builder()
        .filter(Some("minimal_viable_game_engine"), LevelFilter::Info)
        .init();

    let mut world = World::default();

    let mut imgui_prepare_schedule = Schedule::builder()
        .add_system(render::system::imgui_prepare_system())
        .build();

    let mut load_schedule = Schedule::builder()
        .add_system(runtime::system::runtime_load_system())
        .add_system(runtime::system::runtime_spawn_system())
        .flush()
        .build();

    let mut render_schedule = Schedule::builder()
        .add_system(render::system::render_imgui_system())
        .add_system(render::system::render_test_system())
        .add_system(render::system::render_performance_flag_system())
        .build();

    let mut update_schedule = Schedule::builder()
        .add_system(physics::system::update_camera_system())
        .add_system(physics::system::run_physics_system())
        .add_system(physics::system::update_models_system())
        // next system here, gamelogic update system?
        .build();

    let mut event_schedule = Schedule::builder()
        .add_system(owned_event::event_dispatch_system())
        .build();

    let event_loop = EventLoop::<OwnedEventExtension>::with_user_event();
    let mut builder = winit_24::window::WindowBuilder::new();
    builder = builder.with_title("MVGE");
    builder = builder.with_inner_size(PhysicalSize::new(1200,900));

    let window = builder.build(&event_loop).unwrap();

    let mut resources = Resources::default();



    // Load up all the resources
    {
        let mut imgui_context = imgui::Context::create();
        let mut platform = extended_winit_imgui_support::WinitPlatform::init(&mut imgui_context);
        platform.attach_window(
            imgui_context.io_mut(),
            &window,
            extended_winit_imgui_support::HiDpiMode::Default,
        );

        // imgui_supp rendering context
        let mut imgui_context = ImguiContext {
            context: imgui_context,
        };
        let mut imgui_platform = ImguiPlatform { platform: platform };
        let font_size = 20.0 as f32;
        imgui_context.context.io_mut().font_global_scale = 1.0 as f32;
        imgui_context
            .context
            .fonts()
            .add_font(&[FontSource::DefaultFontData {
                config: Some(imgui::FontConfig {
                    oversample_h: 1,
                    pixel_snap_h: true,
                    size_pixels: font_size,
                    ..Default::default()
                }),
            }]);
        imgui_context.context.set_ini_filename(None);

        // The renderer
        let mut renderer = render::state::RenderState::init(&window, &mut imgui_context);

        resources.insert(renderer);
        resources.insert(Arc::new(Mutex::new(imgui_context)));
        resources.insert(Arc::new(Mutex::new(imgui_platform)));
        resources.insert(window);

        // Physics
        let (physics_state, physics_pipeline) =
            PhysicsState::build(rapier3d::math::Vector::new(0.0, -9.81, 0.0));
        resources.insert(physics_state);
        resources.insert(physics_pipeline);

        // Loop data
        resources.insert(LoopState {
            delta_time: Default::default(),
            start_time: Instant::now(),
            step_size: 0.01666, // 60hz
        });

        // And our event stack
        resources.insert(Vec::<OwnedEvent<OwnedEventExtension>>::new());

        // Our init and runtime data
        resources.insert(RuntimeState::new())
    };

    setup_gamepad(&event_loop);

    let mut elapsed_time: f32 = {
        // deltatime since last frame
        let loop_state = resources.get::<LoopState>().unwrap();
        loop_state.start_time.elapsed()
    }
    .as_secs_f32();

    let mut delta_time: f32 = 0.0;
    let mut accumulator_time: f32 = 0.0;
    let mut current_time: f32 = elapsed_time;

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Poll;
        match event {
            event::Event::NewEvents(cause) => {
                if cause == winit_24::event::StartCause::Init {
                    load_schedule.execute(&mut world, &mut resources);
                }
            }

            // This is the big boy section of the event loop
            // We : dispatch events and clear the queue, query the loops
            //      time data and prep the dt data. Loop the dt locked
            //      conditionally, and run the fps locked renderer
            event::Event::MainEventsCleared => {
                event_schedule.execute(&mut world, &mut resources);
                resources
                    .get_mut::<Vec<OwnedEvent<OwnedEventExtension>>>()
                    .unwrap()
                    .clear();

                imgui_prepare_schedule.execute(&mut world, &mut resources);

                let (step_size, elapsed_time) = {
                    let mut loop_state = resources.get_mut::<LoopState>().unwrap();
                    (
                        loop_state.step_size,
                        loop_state.start_time.elapsed().as_secs_f32(),
                    )
                };
                delta_time = elapsed_time - current_time;

                {
                    let mut loop_state = resources.get_mut::<LoopState>().unwrap();
                    loop_state.delta_time = Duration::from_secs_f32(delta_time);
                }
                current_time = elapsed_time;
                if delta_time > 0.02 {
                    delta_time = 0.02;
                }
                accumulator_time += delta_time;

                while accumulator_time - step_size >= step_size {
                    accumulator_time -= step_size;

                    // ==== DELTA TIME LOCKED ====
                    update_schedule.execute(&mut world, &mut resources);
                }
                // ==== FPS LOCKED ====
                render_schedule.execute(&mut world, &mut resources);
            }
            // Resizing will queue a request_redraw
            event::Event::WindowEvent {
                event: WindowEvent::Resized(size),
                ..
            } => {
                let width = size.width;
                let height = size.height;

                resources
                    .get_mut::<render::state::RenderState>()
                    .unwrap()
                    .resize(width, height);
            }
            event::Event::DeviceEvent {
                event: winit_24::event::DeviceEvent::Key(keyboard_input),
                ..
            } => {
                if keyboard_input.virtual_keycode.is_some() {
                    match keyboard_input.virtual_keycode.unwrap() {
                        VirtualKeyCode::Escape => {
                            if keyboard_input.state == ElementState::Pressed {
                                *control_flow = ControlFlow::Exit;
                            } else {
                                //d
                            }
                        }
                        _ => (),
                    }
                }
            }
            event::Event::WindowEvent {
                event: WindowEvent::CloseRequested,
                ..
            } => *control_flow = ControlFlow::Exit,
            event::Event::RedrawRequested(_) => {
                // Call the render system
                //                imgui_prepare_schedule.execute(&mut world, &mut resources);
                //                render_schedule.execute(&mut world, &mut resources);
            }
            _ => {}
        }

        resources
            .get_mut::<Vec<OwnedEvent<OwnedEventExtension>>>()
            .unwrap()
            .push(event.into());
    });
}

pub fn setup_gamepad(event_loop: &EventLoop<OwnedEventExtension>) {
    let event_loop_proxy = event_loop.create_proxy();

    std::thread::spawn(move || {
        let mut gilrs = Gilrs::new().unwrap();
        // Iterate over all connected gamepads
        let mut gamepad: Option<Gamepad> = None;
        for (_id, gamepad_) in gilrs.gamepads() {
            if gamepad_.name() == "PS4" {
                gamepad = Some(gamepad_);
            }
            // println!(
            //     "{} is {:?} {:?}",
            //     gamepad_.name(),
            //     gamepad_.power_info(),
            //     gamepad_.id()
            // );
        }
        let mut active_gamepad = None;

        loop {
            while let Some(GilEvent { id, event, time }) = gilrs.next_event() {
                //println!("{:?} New event from {}: {:?}", time, id, event);
                active_gamepad = Some(id);
                event_loop_proxy
                    .send_event(OwnedEventExtension::GamepadEvent {
                        gil_event: GilEvent { id, event, time },
                    })
                    .ok();
            }

            // // You can also use cached gamepad state
            // if let Some(gamepad) = active_gamepad.map(|id| gilrs.gamepad(id)) {
            //     if gamepad.is_pressed(Button::South) {
            //         println!("Button South is pressed (XBox - A, PS - X)");
            //     }
            // }

            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    });
}
