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

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

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

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

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

/// The [hmtx (Horizontal Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx) table
#[derive(Clone)]
pub struct Hmtx<'a> {
    data: FontData<'a>,
    number_of_h_metrics: u16,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> Hmtx<'a> {
    pub const MIN_SIZE: usize = 0;
    basic_table_impls!(impl_the_methods);

    /// Paired advance width/height and left/top side bearing values for each
    /// glyph. Records are indexed by glyph ID.
    pub fn h_metrics(&self) -> &'a [LongMetric] {
        let range = self.h_metrics_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    /// Leading (left/top) side bearings for glyph IDs greater than or equal to
    /// numberOfLongMetrics.
    pub fn left_side_bearings(&self) -> &'a [BigEndian<i16>] {
        let range = self.left_side_bearings_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

    pub fn h_metrics_byte_range(&self) -> Range<usize> {
        let number_of_h_metrics = self.number_of_h_metrics();
        let start = 0;
        let end = start
            + (transforms::to_usize(number_of_h_metrics)).saturating_mul(LongMetric::RAW_BYTE_LEN);
        start..end
    }

    pub fn left_side_bearings_byte_range(&self) -> Range<usize> {
        let start = self.h_metrics_byte_range().end;
        let end =
            start + self.data.len().saturating_sub(start) / i16::RAW_BYTE_LEN * i16::RAW_BYTE_LEN;
        start..end
    }
}

#[allow(clippy::absurd_extreme_comparisons)]
const _: () = assert!(FontData::default_data_long_enough(Hmtx::MIN_SIZE));

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Hmtx<'a> {
    fn type_name(&self) -> &str {
        "Hmtx"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new(
                "h_metrics",
                traversal::FieldType::array_of_records(
                    stringify!(LongMetric),
                    self.h_metrics(),
                    self.offset_data(),
                ),
            )),
            1usize => Some(Field::new("left_side_bearings", self.left_side_bearings())),
            _ => None,
        }
    }
}

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

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct LongMetric {
    /// Advance width/height, in font design units.
    pub advance: BigEndian<u16>,
    /// Glyph leading (left/top) side bearing, in font design units.
    pub side_bearing: BigEndian<i16>,
}

impl LongMetric {
    /// Advance width/height, in font design units.
    pub fn advance(&self) -> u16 {
        self.advance.get()
    }

    /// Glyph leading (left/top) side bearing, in font design units.
    pub fn side_bearing(&self) -> i16 {
        self.side_bearing.get()
    }
}

impl FixedSize for LongMetric {
    const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for LongMetric {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "LongMetric",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("advance", self.advance())),
                1usize => Some(Field::new("side_bearing", self.side_bearing())),
                _ => None,
            }),
            data,
        }
    }
}
