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

impl<'a> FontRead<'a> for Vorg<'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 [VORG (Vertical Origin)](https://docs.microsoft.com/en-us/typography/opentype/spec/vorg) table.
#[derive(Clone)]
pub struct Vorg<'a> {
    data: FontData<'a>,
}

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

    /// Major/minor version number. Set to 1.0.
    pub fn version(&self) -> MajorMinor {
        let range = self.version_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// The y coordinate of a glyph’s vertical origin, in the font’s design
    /// coordinate system, to be used if no entry is present for the glyph
    /// in the vertOriginYMetrics array.
    pub fn default_vert_origin_y(&self) -> i16 {
        let range = self.default_vert_origin_y_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Number of elements in the vertOriginYMetrics array.
    pub fn num_vert_origin_y_metrics(&self) -> u16 {
        let range = self.num_vert_origin_y_metrics_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of VertOriginYMetrics records, sorted by glyph ID.
    pub fn vert_origin_y_metrics(&self) -> &'a [VertOriginYMetrics] {
        let range = self.vert_origin_y_metrics_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

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

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

    pub fn vert_origin_y_metrics_byte_range(&self) -> Range<usize> {
        let num_vert_origin_y_metrics = self.num_vert_origin_y_metrics();
        let start = self.num_vert_origin_y_metrics_byte_range().end;
        start
            ..start
                + (num_vert_origin_y_metrics as usize)
                    .saturating_mul(VertOriginYMetrics::RAW_BYTE_LEN)
    }
}

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Vorg<'a> {
    fn type_name(&self) -> &str {
        "Vorg"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new(
                "default_vert_origin_y",
                self.default_vert_origin_y(),
            )),
            2usize => Some(Field::new(
                "num_vert_origin_y_metrics",
                self.num_vert_origin_y_metrics(),
            )),
            3usize => Some(Field::new(
                "vert_origin_y_metrics",
                traversal::FieldType::array_of_records(
                    stringify!(VertOriginYMetrics),
                    self.vert_origin_y_metrics(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

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

/// Vertical origin Y metrics record.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct VertOriginYMetrics {
    /// Glyph index.
    pub glyph_index: BigEndian<GlyphId16>,
    /// Y coordinate, in the font’s design coordinate system, of the glyph’s vertical origin.
    pub vert_origin_y: BigEndian<i16>,
}

impl VertOriginYMetrics {
    /// Glyph index.
    pub fn glyph_index(&self) -> GlyphId16 {
        self.glyph_index.get()
    }

    /// Y coordinate, in the font’s design coordinate system, of the glyph’s vertical origin.
    pub fn vert_origin_y(&self) -> i16 {
        self.vert_origin_y.get()
    }
}

impl FixedSize for VertOriginYMetrics {
    const RAW_BYTE_LEN: usize = GlyphId16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
}

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