// 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::*;

/// [`meta`](https://docs.microsoft.com/en-us/typography/opentype/spec/meta)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MetaMarker {
    data_maps_byte_len: usize,
}

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

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

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

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

    pub fn data_maps_byte_range(&self) -> Range<usize> {
        let start = self.data_maps_count_byte_range().end;
        start..start + self.data_maps_byte_len
    }
}

impl MinByteRange for MetaMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.data_maps_byte_range().end
    }
}

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

impl<'a> FontRead<'a> for Meta<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u32>();
        cursor.advance::<u32>();
        cursor.advance::<u32>();
        let data_maps_count: u32 = cursor.read()?;
        let data_maps_byte_len = (data_maps_count as usize)
            .checked_mul(DataMapRecord::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(data_maps_byte_len);
        cursor.finish(MetaMarker { data_maps_byte_len })
    }
}

/// [`meta`](https://docs.microsoft.com/en-us/typography/opentype/spec/meta)
pub type Meta<'a> = TableRef<'a, MetaMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> Meta<'a> {
    /// Version number of the metadata table — set to 1.
    pub fn version(&self) -> u32 {
        let range = self.shape.version_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Flags — currently unused; set to 0.
    pub fn flags(&self) -> u32 {
        let range = self.shape.flags_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// The number of data maps in the table.
    pub fn data_maps_count(&self) -> u32 {
        let range = self.shape.data_maps_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Array of data map records.
    pub fn data_maps(&self) -> &'a [DataMapRecord] {
        let range = self.shape.data_maps_byte_range();
        self.data.read_array(range).unwrap()
    }
}

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

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

///  <https://learn.microsoft.com/en-us/typography/opentype/spec/meta#table-formats>
#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct DataMapRecord {
    /// A tag indicating the type of metadata.
    pub tag: BigEndian<Tag>,
    /// Offset in bytes from the beginning of the metadata table to the data for this tag.
    pub data_offset: BigEndian<Offset32>,
    /// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
    pub data_length: BigEndian<u32>,
}

impl DataMapRecord {
    /// A tag indicating the type of metadata.
    pub fn tag(&self) -> Tag {
        self.tag.get()
    }

    /// Offset in bytes from the beginning of the metadata table to the data for this tag.
    pub fn data_offset(&self) -> Offset32 {
        self.data_offset.get()
    }

    /// Offset in bytes from the beginning of the metadata table to the data for this tag.
    ///
    /// The `data` argument should be retrieved from the parent table
    /// By calling its `offset_data` method.
    pub fn data<'a>(&self, data: FontData<'a>) -> Result<Metadata<'a>, ReadError> {
        let args = (self.tag(), self.data_length());
        self.data_offset().resolve_with_args(data, &args)
    }

    /// Length of the data, in bytes. The data is not required to be padded to any byte boundary.
    pub fn data_length(&self) -> u32 {
        self.data_length.get()
    }
}

impl FixedSize for DataMapRecord {
    const RAW_BYTE_LEN: usize = Tag::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}

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