// 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 BaseArray<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.face_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 ReadArgs for BaseArray<'_> {
    type Args = u16;
}

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

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

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

#[derive(Clone)]
pub struct BaseArray<'a> {
    data: FontData<'a>,
    mark_class_count: u16,
}

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

    /// Number of BaseRecords
    pub fn base_count(&self) -> u16 {
        let range = self.base_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of BaseRecords, in order of baseCoverage Index.
    pub fn base_records(&self) -> ComputedArray<'a, BaseRecord<'a>> {
        let range = self.base_records_byte_range();
        self.data
            .read_with_args(range, &self.mark_class_count())
            .unwrap_or_default()
    }

    pub fn face_count(&self) -> u16 {
        let range = self.face_count_byte_range();
        self.data.read_at(range.start).ok().unwrap_or_default()
    }

    pub fn face_records(&self) -> ComputedArray<'a, FaceRecord<'a>> {
        let range = self.face_records_byte_range();
        self.data
            .read_with_args(range, &self.mark_class_count())
            .unwrap_or_default()
    }

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

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

    pub fn base_records_byte_range(&self) -> Range<usize> {
        let base_count = self.base_count();
        let start = self.base_count_byte_range().end;
        start
            ..start
                + (base_count as usize).saturating_mul(
                    <BaseRecord as ComputeSize>::compute_size(&self.mark_class_count())
                        .unwrap_or(0),
                )
    }

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

    pub fn face_records_byte_range(&self) -> Range<usize> {
        let base_count = self.base_count();
        let start = self.face_count_byte_range().end;
        start
            ..start
                + (base_count as usize).saturating_mul(
                    <FaceRecord as ComputeSize>::compute_size(&self.mark_class_count())
                        .unwrap_or(0),
                )
    }
}

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for BaseArray<'a> {
    fn type_name(&self) -> &str {
        "BaseArray"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("base_count", self.base_count())),
            1usize => Some(Field::new(
                "base_records",
                traversal::FieldType::computed_array(
                    "BaseRecord",
                    self.base_records(),
                    self.offset_data(),
                ),
            )),
            2usize => Some(Field::new("face_count", self.face_count())),
            3usize => Some(Field::new(
                "face_records",
                traversal::FieldType::computed_array(
                    "FaceRecord",
                    self.face_records(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

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

/// Contains a scalar array
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BaseRecord<'a> {
    /// Array of offsets (one per mark class) to Anchor tables. Offsets
    /// are from beginning of BaseArray table, ordered by class
    /// (offsets may be NULL).
    pub base_anchor_offsets: &'a [BigEndian<u16>],
}

impl<'a> BaseRecord<'a> {
    /// Array of offsets (one per mark class) to Anchor tables. Offsets
    /// are from beginning of BaseArray table, ordered by class
    /// (offsets may be NULL).
    pub fn base_anchor_offsets(&self) -> &'a [BigEndian<u16>] {
        self.base_anchor_offsets
    }
}

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

impl ComputeSize for BaseRecord<'_> {
    #[allow(clippy::needless_question_mark)]
    fn compute_size(args: &u16) -> Result<usize, ReadError> {
        let mark_class_count = *args;
        Ok((mark_class_count as usize).saturating_mul(u16::RAW_BYTE_LEN))
    }
}

impl<'a> FontReadWithArgs<'a> for BaseRecord<'a> {
    fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let mark_class_count = *args;
        Ok(Self {
            base_anchor_offsets: cursor.read_array(mark_class_count as usize)?,
        })
    }
}

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

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

/// Contains offsets
#[derive(Clone, Debug)]
pub struct FaceRecord<'a> {
    pub face_offsets: &'a [BigEndian<Nullable<Offset16>>],
}

impl<'a> FaceRecord<'a> {
    pub fn face_offsets(&self) -> &'a [BigEndian<Nullable<Offset16>>] {
        self.face_offsets
    }

    ///
    /// The `data` argument should be retrieved from the parent table
    /// By calling its `offset_data` method.
    pub fn faces(&self, data: FontData<'a>) -> ArrayOfNullableOffsets<'a, Face<'a>, Offset16> {
        let offsets = self.face_offsets();
        ArrayOfNullableOffsets::new(offsets, data, ())
    }
}

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

impl ComputeSize for FaceRecord<'_> {
    #[allow(clippy::needless_question_mark)]
    fn compute_size(args: &u16) -> Result<usize, ReadError> {
        let mark_class_count = *args;
        Ok((mark_class_count as usize).saturating_mul(Offset16::RAW_BYTE_LEN))
    }
}

impl<'a> FontReadWithArgs<'a> for FaceRecord<'a> {
    fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let mark_class_count = *args;
        Ok(Self {
            face_offsets: cursor.read_array(mark_class_count as usize)?,
        })
    }
}

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

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

impl<'a> MinByteRange<'a> for Face<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.field_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<'a> FontRead<'a> for Face<'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 })
    }
}

#[derive(Clone)]
pub struct Face<'a> {
    data: FontData<'a>,
}

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

    pub fn field(&self) -> u16 {
        let range = self.field_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Face<'a> {
    fn type_name(&self) -> &str {
        "Face"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("field", self.field())),
            _ => None,
        }
    }
}

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