use std::sync::Arc;

use vulkano::command_buffer::DynamicState;
use vulkano::device::Device;
use vulkano::format::Format;
use vulkano::framebuffer::{Framebuffer, FramebufferAbstract, RenderPassAbstract};
use vulkano::image::{AttachmentImage, ImageUsage, SwapchainImage};
use vulkano::pipeline::viewport::Viewport;
use winit::window::Window;
use vulkano::swapchain::Swapchain;

/// This method is called once during initialization, then again whenever the window is resized
pub fn create_framebuffers(device: Arc<Device>,
                           swapchain: &Arc<Swapchain<Window>>,
                           images: &[Arc<SwapchainImage<Window>>],
                           msaa_sample_count: u32,
                           render_pass: Arc<dyn RenderPassAbstract + Send + Sync>,
                           dynamic_state: &mut DynamicState)
                                -> Vec<Arc<dyn FramebufferAbstract + Send + Sync>> {

    let dim_array = images[0].dimensions();
    let dim_array_f32 = [dim_array[0] as f32, dim_array[1] as f32];

    let viewport = Viewport {
        origin: [0.0, 0.0],
        dimensions: dim_array_f32,
        depth_range: 0.0..1.0,
    };
    dynamic_state.viewports = Some(vec!(viewport));

    let depth_image = if msaa_sample_count > 0 {
        AttachmentImage::multisampled_with_usage(device.clone(), dim_array, msaa_sample_count, Format::D16Unorm, ImageUsage { depth_stencil_attachment: true, ..ImageUsage::none() }).unwrap()
    } else {
        AttachmentImage::with_usage(device.clone(), dim_array, Format::D16Unorm, ImageUsage { depth_stencil_attachment: true, ..ImageUsage::none() }).unwrap()
    };

    let msaa_buffers = if msaa_sample_count > 0 {
        Some(create_msaa_buffers(device.clone(), dim_array, swapchain, msaa_sample_count))
    } else {
        None
    };

    let mut framebuffers = vec![];

    for i in 0..images.len() {
        let image_buffer = &images[i];

        if let Some(msaa_buffers_exist) = &msaa_buffers {
            framebuffers.push(Arc::new(Framebuffer::start(render_pass.clone())
                .add(image_buffer.clone()).unwrap()
                .add((&msaa_buffers_exist[i]).clone()).unwrap()
                .add(depth_image.clone()).unwrap()
                .build().unwrap()
            ) as Arc<dyn FramebufferAbstract + Send + Sync>);
        } else {
            framebuffers.push(Arc::new(Framebuffer::start(render_pass.clone())
                .add(image_buffer.clone()).unwrap()
                .add(depth_image.clone()).unwrap()
                .build().unwrap()
            ) as Arc<dyn FramebufferAbstract + Send + Sync>);
        }
    }

    framebuffers
}

fn create_msaa_buffers(device: Arc<Device>, dimensions: [u32; 2], swapchain: &Arc<Swapchain<Window>>, sample_count: u32) -> Vec<Arc<AttachmentImage>> {
    let mut msaa_attachments = vec![];
    for _ in 0..swapchain.num_images() {
        msaa_attachments.push(AttachmentImage::transient_multisampled(device.clone(), dimensions, sample_count, swapchain.format()).unwrap());
    }
    msaa_attachments
}