use super::MeshPass;

impl MeshPass {
    pub fn apply_material_textures(
        &mut self,
        device: &wgpu::Device,
        arrays: &crate::render::wgpu::material_texture_arrays::MaterialTextureArrays,
    ) {
        if self.material_bindless_max.is_some() && arrays.is_bindless() {
            let views = arrays.bindless_view_refs();
            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("Mesh Material Bindless Bind Group"),
                layout: &self.texture_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureViewArray(&views),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(arrays.sampler()),
                    },
                ],
            });
            self.material_bind_group = Some(bind_group);
            return;
        }

        self.material_array_srgb_view = Some(arrays.srgb_view().clone());
        self.material_array_linear_view = Some(arrays.linear_view().clone());
        self.material_array_sampler = Some(arrays.sampler().clone());
        self.rebuild_material_bind_group(device);
    }

    pub(in super::super) fn rebuild_material_bind_group(&mut self, device: &wgpu::Device) {
        let (Some(srgb), Some(linear), Some(sampler)) = (
            self.material_array_srgb_view.as_ref(),
            self.material_array_linear_view.as_ref(),
            self.material_array_sampler.as_ref(),
        ) else {
            self.material_bind_group = None;
            return;
        };

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Mesh Material Texture Bind Group"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(srgb),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(linear),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
            ],
        });

        self.material_bind_group = Some(bind_group);
    }
}
