use std::sync::Arc;

use vulkano::device::Device;
use vulkano::format::Format;
use vulkano::image::view::ImageView;
use vulkano::image::{AttachmentImage, ImageUsage, SampleCount, SwapchainImage};
use vulkano::render_pass::{Framebuffer, FramebufferAbstract, RenderPass};
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: Option<SampleCount>,
                           render_pass: Arc<RenderPass>)
                                -> Vec<Arc<dyn FramebufferAbstract + Send + Sync>> {

    let dim_array = images[0].dimensions();

    let depth_image = if let Some(sample_count) = msaa_sample_count {
        AttachmentImage::multisampled_with_usage(device.clone(), dim_array, sample_count, Format::D16_UNORM, ImageUsage { depth_stencil_attachment: true, ..ImageUsage::none() }).unwrap()
    } else {
        AttachmentImage::with_usage(device.clone(), dim_array, Format::D16_UNORM, ImageUsage { depth_stencil_attachment: true, ..ImageUsage::none() }).unwrap()
    };
    let depth_image_view = ImageView::new(depth_image.clone()).unwrap();

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

    let mut framebuffers = vec![];

    for i in 0..images.len() {
        let image_buffer = &images[i];
        let view = ImageView::new(image_buffer.clone()).unwrap();

        if let Some(msaa_buffers_exist) = &msaa_buffers {
            let msaa_view = ImageView::new((&msaa_buffers_exist[i]).clone()).unwrap();
            
            framebuffers.push(Arc::new(Framebuffer::start(render_pass.clone())
                .add(view).unwrap()
                .add(msaa_view).unwrap()
                .add(depth_image_view.clone()).unwrap()
                .build().unwrap()
            ) as Arc<dyn FramebufferAbstract + Send + Sync>);
        } else {
            framebuffers.push(Arc::new(Framebuffer::start(render_pass.clone())
                .add(view).unwrap()
                .add(depth_image_view.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: SampleCount) -> 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
}