/*
 *    Copyright 2025 Jared Davis
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */


use crate::rgb::RGB;
use crate::xyz::{Illumination, XYZ};

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Lab {
    pub l: f32,
    pub a: f32,
    pub b: f32,
}

impl Lab {
    pub fn xyz(self, illumination: Illumination) -> XYZ {
        let l = (self.l + 16.0) * 0.008620689655;
        let a = self.a * 0.002;
        let b = self.b * 0.005;

        let x = reverse(l + a) / illumination.reference.x;
        let y = (reverse(l)) / illumination.reference.y;
        let z = reverse(l - b) / illumination.reference.z;

        XYZ { x, y, z }
    }

    pub fn rgb(self, illumination: Illumination) -> RGB {
        self.xyz(illumination).rgb(illumination)
    }
}

fn reverse(v: f32) -> f32 {
    let u = v.powf(3.0);
    if u > 8.8565e-03 {
        u
    } else {
        (v - 0.1379) * 0.1284
    }
}