// 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 Hdmx<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.records_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 Hdmx<'_> {
    /// `hdmx`
    const TAG: Tag = Tag::new(b"hdmx");
}

impl ReadArgs for Hdmx<'_> {
    type Args = u16;
}

impl<'a> FontReadWithArgs<'a> for Hdmx<'a> {
    fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
        let num_glyphs = *args;

        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data, num_glyphs })
    }
}

impl<'a> Hdmx<'a> {
    /// A constructor that requires additional arguments.
    ///
    /// This type requires some external state in order to be
    /// parsed.
    pub fn read(data: FontData<'a>, num_glyphs: u16) -> Result<Self, ReadError> {
        let args = num_glyphs;
        Self::read_with_args(data, &args)
    }
}

/// The [Horizontal Device Metrics](https://learn.microsoft.com/en-us/typography/opentype/spec/hdmx) table.
#[derive(Clone)]
pub struct Hdmx<'a> {
    data: FontData<'a>,
    num_glyphs: u16,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> Hdmx<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Table version number (set to 0).
    pub fn version(&self) -> u16 {
        let range = self.version_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Number of device records.
    pub fn num_records(&self) -> u16 {
        let range = self.num_records_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Size of device record, 32-bit aligned.
    pub fn size_device_record(&self) -> u32 {
        let range = self.size_device_record_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of device records.
    pub fn records(&self) -> ComputedArray<'a, DeviceRecord<'a>> {
        let range = self.records_byte_range();
        self.data
            .read_with_args(range, &(self.num_glyphs(), self.size_device_record()))
            .unwrap_or_default()
    }

    pub(crate) fn num_glyphs(&self) -> u16 {
        self.num_glyphs
    }

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

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

    pub fn size_device_record_byte_range(&self) -> Range<usize> {
        let start = self.num_records_byte_range().end;
        start..start + u32::RAW_BYTE_LEN
    }

    pub fn records_byte_range(&self) -> Range<usize> {
        let num_records = self.num_records();
        let start = self.size_device_record_byte_range().end;
        start
            ..start
                + (num_records as usize).saturating_mul(
                    <DeviceRecord as ComputeSize>::compute_size(&(
                        self.num_glyphs(),
                        self.size_device_record(),
                    ))
                    .unwrap_or(0),
                )
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hdmx<'a> {
    fn type_name(&self) -> &str {
        "Hdmx"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new("num_records", self.num_records())),
            2usize => Some(Field::new("size_device_record", self.size_device_record())),
            3usize => Some(Field::new(
                "records",
                traversal::FieldType::computed_array(
                    "DeviceRecord",
                    self.records(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

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