use crate::utils::read_float_file;
use anyhow::Result;
use shared::core::color::{Coeffs, RES, RGBToSpectrumTable};
use shared::{Float, Ptr, gvec_from_slice};
use std::ops::Deref;
use std::path::Path;

pub trait CreateRGBToSpectrumTable {
    fn new(z_nodes: &[Float], coeffs: &[Float]) -> Self;
    fn load(base_dir: &Path, name: &str) -> Result<Self> where Self: Sized;
}

impl CreateRGBToSpectrumTable for RGBToSpectrumTable {
    fn new(z_nodes: &[Float], coeffs: &[Float]) -> Self {
        assert_eq!(z_nodes.len(), RES as usize);
        assert_eq!(coeffs.len(), (RES * RES * RES) as usize * 3 * 3);
        Self {
            z_nodes: gvec_from_slice(z_nodes),
            coeffs: gvec_from_slice(unsafe {
                core::slice::from_raw_parts(
                    coeffs.as_ptr() as *const Coeffs,
                    coeffs.len() / 3,
                )
            }),
        }
    }

    fn load(base_dir: &Path, name: &str) -> Result<Self> {
        let scale = read_float_file(base_dir.join(format!("{}_scale.dat", name)).to_str().unwrap())?;
        let coeffs = read_float_file(base_dir.join(format!("{}_coeffs.dat", name)).to_str().unwrap())?;
        Ok(Self::new(&scale, &coeffs))
    }
}
