// THIS FILE IS AUTOGENERATED.
// Any changes to this file will be overwritten.
// For more information about how codegen works, see font-codegen/README.md

#[allow(unused_imports)]
use crate::codegen_prelude::*;

impl<'a> MinByteRange<'a> for Cvar<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.tuple_variation_headers_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl TopLevelTable for Cvar<'_> {
    /// `cvar`
    const TAG: Tag = Tag::new(b"cvar");
}

impl<'a> FontRead<'a> for Cvar<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// The [cvar](https://learn.microsoft.com/en-us/typography/opentype/spec/cvar) table.
#[derive(Clone)]
pub struct Cvar<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> Cvar<'a> {
    pub const MIN_SIZE: usize =
        (MajorMinor::RAW_BYTE_LEN + TupleVariationCount::RAW_BYTE_LEN + Offset16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Major/minor version number of the CVT variations table — set to (1,0).
    pub fn version(&self) -> MajorMinor {
        let range = self.version_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// A packed field. The high 4 bits are flags, and the low 12 bits
    /// are the number of tuple variation tables for this glyph. The
    /// number of tuple variation tables can be any number between 1
    /// and 4095.
    pub fn tuple_variation_count(&self) -> TupleVariationCount {
        let range = self.tuple_variation_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Offset from the start of the 'cvar' table to the serialized data.
    pub fn data_offset(&self) -> Offset16 {
        let range = self.data_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`data_offset`][Self::data_offset].
    pub fn data(&self) -> Result<FontData<'a>, ReadError> {
        let data = self.data;
        self.data_offset().resolve(data)
    }

    /// Array of tuple variation headers.
    pub fn tuple_variation_headers(&self) -> VarLenArray<'a, TupleVariationHeader<'a>> {
        let range = self.tuple_variation_headers_byte_range();
        self.data
            .split_off(range.start)
            .and_then(|d| VarLenArray::read(d).ok())
            .unwrap_or_default()
    }

    pub fn version_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + MajorMinor::RAW_BYTE_LEN
    }

    pub fn tuple_variation_count_byte_range(&self) -> Range<usize> {
        let start = self.version_byte_range().end;
        start..start + TupleVariationCount::RAW_BYTE_LEN
    }

    pub fn data_offset_byte_range(&self) -> Range<usize> {
        let start = self.tuple_variation_count_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn tuple_variation_headers_byte_range(&self) -> Range<usize> {
        let start = self.data_offset_byte_range().end;
        start..start + self.data.len().saturating_sub(start)
    }
}

const _: () = assert!(FontData::default_data_long_enough(Cvar::MIN_SIZE));

impl Default for Cvar<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Cvar<'a> {
    fn type_name(&self) -> &str {
        "Cvar"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new(
                "tuple_variation_count",
                traversal::FieldType::Unknown,
            )),
            2usize => Some(Field::new("data_offset", traversal::FieldType::Unknown)),
            3usize => Some(Field::new(
                "tuple_variation_headers",
                traversal::FieldType::Unknown,
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Cvar<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}
