use super::super::super::material_gpu;
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();
            self.material_bind_group = Some(material_gpu::bindless_material_bind_group(
                device,
                &self.texture_bind_group_layout,
                &views,
                arrays.sampler(),
                "Mesh Material Bindless 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;
        };

        self.material_bind_group = Some(material_gpu::array_material_bind_group(
            device,
            &self.texture_bind_group_layout,
            srgb,
            linear,
            sampler,
            "Mesh Material Texture Bind Group",
        ));
    }
}
