#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_mut)]


extern crate cgmath;
extern crate hprof;
extern crate image;
extern crate nalgebra as na;
extern crate rand;
extern crate time;

use std::path::Path;
use std::sync::Arc;

use gilrs::{Button, Event as GilEvent, Gamepad, GamepadId, Gilrs};
use vulkano::instance::debug::DebugCallback;
use vulkano::instance::Instance;
use vulkano::sync;
use vulkano::sync::GpuFuture;
use vulkano_win::VkSurfaceBuild;
use winit::dpi::LogicalSize;
use winit::event::{DeviceEvent, ElementState, Event, MouseButton, StartCause, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop, EventLoopProxy};
use winit::platform::unix::WindowBuilderExtUnix;
use winit::window::WindowBuilder;

use crate::canvas::canvas_frame::{CanvasFrame, Drawable, Eventable, Updatable};
use crate::canvas::canvas_state::CanvasState;
use crate::canvas::managed::handles::{CanvasFontHandle, CanvasTextureHandle, Handle};
use crate::compute::compu_frame::CompuFrame;
use crate::compute::managed::handles::{CompuBufferHandle, CompuKernelHandle};
use crate::drawables::compu_sprite::CompuSprite;
use crate::drawables::rect::Rect;
use crate::drawables::sprite::Sprite;
use crate::drawables::text::Text;
use crate::util::load_raw;
use crate::util::timer::Timer;
use crate::util::tr_event::TrEvent;
use crate::util::vertex::{TextureVertex3D, VertexTypeContainer};
use crate::vkprocessor::VkProcessor;
use crate::drawables::slider::Slider;

pub mod util;
pub mod vkprocessor;
pub mod drawables;
pub mod canvas;
pub mod compute;


extern crate specs;

use specs::prelude::*;


struct Draws(VertexTypeContainer);

impl Component for Draws {
    type Storage = VecStorage<Self>;
}

struct Renderer(u32);

struct Vel(f32);

impl Component for Vel {
    type Storage = VecStorage<Self>;
}

struct Pos(f32);

impl Component for Pos {
    type Storage = VecStorage<Self>;
}

struct RenderSystem;

impl<'a> System<'a> for RenderSystem {

    type SystemData = (
        WriteStorage<'a, Pos>,
        WriteStorage<'a, Vel>,
        WriteStorage<'a, Draws>,
    );

    fn run(&mut self, (mut pos, vel, data): Self::SystemData) {

        // The `.join()` combines multiple components,
        // so we only access those entities which have
        // both of them.

        // This joins the component storages for Position
        // and Velocity together; it's also possible to do this
        // in parallel using rayon's `ParallelIterator`s.
        // See `ParJoin` for more.
        for (pos, vel) in (&mut pos, &vel).join() {
            pos.0 += vel.0;
        }
    }
}

struct SysA;

impl<'a> System<'a> for SysA {
    // These are the resources required for execution.
    // You can also define a struct and `#[derive(SystemData)]`,
    // see the `full` example.
    type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>);

    fn run(&mut self, (mut pos, vel): Self::SystemData) {
        // The `.join()` combines multiple components,
        // so we only access those entities which have
        // both of them.

        // This joins the component storages for Position
        // and Velocity together; it's also possible to do this
        // in parallel using rayon's `ParallelIterator`s.
        // See `ParJoin` for more.
        for (pos, vel) in (&mut pos, &vel).join() {
            pos.0 += vel.0;
        }
    }
}


pub fn main() {

    hprof::start_frame();

    let q1 = hprof::enter("setup");

    let instance = {
        let extensions = vulkano_win::required_extensions();
        Instance::new(None, &extensions, None).unwrap()
    };

    let _callback = DebugCallback::errors_and_warnings(&instance, |msg| {
        println!("Debug callback: {:?}", msg.description);
    }).ok();

    let mut events_loop = EventLoop::<TrEvent>::with_user_event();

    let mut surface = WindowBuilder::new()
        .with_inner_size(LogicalSize::new(800, 800))
        .build_vk_surface(&events_loop, instance.clone()).unwrap();

    let mut processor = VkProcessor::new(instance.clone(), surface.clone());

    {
        let g = hprof::enter("vulkan preload");
        processor.create_swapchain(instance.clone(), surface.clone());
        processor.preload_kernels();
        processor.preload_shaders();
        processor.preload_textures();
        processor.preload_fonts();
    }

    let q2 = hprof::enter("Game Objects");

    let mut timer = Timer::new();
    let mut frame_future: Box<dyn GpuFuture> =
        Box::new(sync::now(processor.device.clone())) as Box<dyn GpuFuture>;

    let step_size: f32 = 0.005;
    let mut elapsed_time: f32 = timer.elap_time();

    let mut delta_time: f32 = 0.0;
    let mut accumulator_time: f32 = 0.0;
    let mut current_time: f32 = timer.elap_time();

    let image_data = load_raw(String::from("ford2.jpg"));
    let image_dimensions_f: (f32, f32) = ((image_data.1).clone().0 as f32, (image_data.1).clone().1 as f32);
    let image_dimensions_u: (u32, u32) = image_data.1;
    let compu_sprite1: CompuSprite =
        CompuSprite::new((-1.0, -1.0), (1.0, 1.0), 0, image_dimensions_f,
                         // Swap image to render the result to. Must match dimensions
                         processor.new_swap_image(image_dimensions_u));

    // Need to
    let compute_buffer: Arc<CompuBufferHandle> =
        processor.new_compute_buffer(image_data.0.clone(), image_data.1, 4);

    let first_output_buffer: Arc<CompuBufferHandle> =
        processor.new_compute_buffer(image_data.0.clone(), image_data.1.clone(), 4);

    let compute_kernel: Arc<CompuKernelHandle> =
        processor.get_kernel_handle(String::from("simple-edge.compute"))
            .expect("Can't find that kernel");

    // Get the handles for the assets
    let funky_handle: Arc<CanvasTextureHandle> =
        processor.get_texture_handle(String::from("funky-bird.jpg")).unwrap();
    let sfml_handle: Arc<CanvasTextureHandle> =
        processor.get_texture_handle(String::from("sfml.png")).unwrap();
    //let font_handle : Arc<CanvasFontHandle> =
    //    processor.get_font_handle(String::from("sansation.ttf")).unwrap();







    // The `World` is our
    // container for components
    // and other resources.

    let mut world = World::new();
    world.register::<Pos>();
    world.register::<Vel>();
    world.register::<Draws>();
    world.insert::<Renderer>(Renderer(10));
    world.insert::<VkProcessor>(processor);


    // An entity may or may not contain some component.
    world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build();

    let mut dispatcher = DispatcherBuilder::new()
        .with(SysA, "sys_a", &[])
        .with(RenderSystem, "render_s", &[]).build();

    // This dispatches all the systems in parallel (but blocking).
    dispatcher.dispatch(&mut world);








    let mut funky_sprite = Sprite::new(
        (200.0, 200.0),
        (100.0, 150.0), 10, funky_handle.clone());
    let sfml_sprite = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone());

    let slider = Slider::new((300.0, 50.0), (550.0, 100.0), 30000);

    //let sfml_sprite  = Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone());
    //let text_sprite = Text::new((-0.1, -0.1), (10.0, 10.0), 1);
    //let test_polygon = Poly::new_with_color((-0.5, -0.5), (0.5, 0.5), 1, (1.0,0.0,0.0,0.0));

    drop(q2);
    drop(q1);

    let l = hprof::enter("Loop");

    let event_loop_proxy = events_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(TrEvent::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));
        }
    });

    let mut window_size: (u32, u32) = (0, 0);

    let mut canvas_frame = CanvasFrame::new(window_size);
    let mut compu_frame = CompuFrame::new(window_size);



    // What would the component for a sprite be...
    // Drawable with the vertex format in one rendering system
    // position + velocity could then be two more in one system
    // maybe some sort of input system

    //
    // let mut big_container = vec![
    //     Box::new(Slider::new((0.1, 0.1), (0.9, 0.9), 5000)),
    //     Box::new(Sprite::new((0.0, -0.5), (0.5, 0.5), 1, sfml_handle.clone())),
    // ];
    //container.push(Sprite::new((0.1)));


    // Events loop is borrowed from the surface
    events_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Poll;

        // for eventable in &mut big_container {
        //     eventable.notify(&event);
        // }
        //
        // for drawable in &mut big_container {
        //     canvas_frame.draw(&drawable);
        // }

        match event {
            Event::NewEvents(cause) => {
                if cause == StartCause::Init {
                    canvas_frame.draw(&funky_sprite);
                    canvas_frame.draw(&compu_sprite1);
                    canvas_frame.draw(&slider);

                    window_size = surface.window().inner_size().into();
                }
                elapsed_time = timer.elap_time();
                delta_time = elapsed_time - current_time;
                current_time = elapsed_time;
                if delta_time > 0.02 {
                    delta_time = 0.02;
                }
                accumulator_time += delta_time;
            }
            Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
                *control_flow = ControlFlow::Exit
            }
            Event::WindowEvent { event: WindowEvent::Resized(new_size), .. } => {
                world.write_resource::<VkProcessor>().swapchain_recreate_needed = true;
                let size = (new_size.width, new_size.height);
            }
            Event::WindowEvent {
                event: WindowEvent::MouseInput {
                    device_id, state, button, modifiers
                }, ..
            } => {}
            Event::UserEvent(TrEvent::KeyHeldEvent {}) => {}
            Event::UserEvent(TrEvent::MouseHeldEvent {}) => {}
            Event::UserEvent(TrEvent::GamepadEvent { gil_event }) => {}
            Event::DeviceEvent { device_id, event } => {
                match event {
                    DeviceEvent::Key(keyboard_input) => {
                        match keyboard_input.virtual_keycode.unwrap() {
                            VirtualKeyCode::A => {
                                if keyboard_input.state == ElementState::Pressed {}
                            }
                            VirtualKeyCode::S => {
                                if keyboard_input.state == ElementState::Pressed {}
                            }
                            VirtualKeyCode::P => {
                                if keyboard_input.state == ElementState::Pressed {
                                    let data = world.write_resource::<VkProcessor>().read_compute_buffer(compute_buffer.clone());
                                    image::save_buffer(&Path::new("image.png"), data.as_slice(), (image_data.1).0, (image_data.1).1, image::RGBA(8));
                                }
                            }
                            _ => ()
                        }
                    }
                    _ => {}
                }
            }

            Event::MainEventsCleared => {
                funky_sprite.update(delta_time);

                canvas_frame = CanvasFrame::new(window_size);
                canvas_frame.draw(&funky_sprite);
                //canvas_frame.draw(&container);
                // canvas_frame.draw(&compu_sprite1);
                canvas_frame.draw(&slider);

                compu_frame = CompuFrame::new(window_size);
                // compu_frame.add_with_image_swap(compute_buffer.clone(), compute_kernel.clone(), &compu_sprite1);
                // compu_frame.add(compute_buffer.clone(), compute_kernel.clone());

                {
                    let g = hprof::enter("Run");
                    world.write_resource::<VkProcessor>()
                        .run(&surface.clone(),
                                  &canvas_frame,
                                  &compu_frame);
                }

                //     while (accumulator_time - step_size) >= step_size {
                //         accumulator_time -= step_size;
                //     }
            }
            _ => ()
        }

        // bucket the events out, but not really
        // match
        // event {
        //     Event::NewEvents(_) => {}
        //     Event::WindowEvent { window_id, event } => {}
        //     Event::DeviceEvent { device_id, event } => {}
        //     Event::UserEvent(tr_event) => {}
        //     Event::Suspended => {}
        //     Event::Resumed => {}
        //     Event::MainEventsCleared => {}
        //     Event::RedrawRequested(_) => {}
        //     Event::RedrawEventsCleared => {}
        //     Event::LoopDestroyed => {}
        // }
    });

    drop(l);

    hprof::end_frame();
    hprof::profiler().print_timing();
}


pub fn click_test(event_loop_proxy: EventLoopProxy<TrEvent>, canvas_state: &CanvasState) {
    // for i in canvas_state. {
    //     event_loop_proxy.send_event(TrEvent::MouseClickEvent {
    //         position: (0.0, 0.0),
    //         button: MouseButton::Left,
    //     }).ok();
    // }
}



















