use crate::inspect::smp::structures::*;

#[derive(Clone)]
pub(super) struct EmbeddedNameRow {
    pub(super) name_tag_relative_offset: usize,
    pub(super) prefix_leading_dword: u32,
    pub(super) prefix_trailing_word: u16,
    pub(super) prefix_separator_byte: u8,
    pub(super) name_payload_relative_offset: usize,
    pub(super) name_payload_len: usize,
    pub(super) primary_name: Option<String>,
    pub(super) secondary_name: Option<String>,
    pub(super) tertiary_name: Option<String>,
}

pub(super) fn parse_embedded_name_rows(
    records_payload: &[u8],
    embedded_name_tag_offsets: &[usize],
) -> Vec<EmbeddedNameRow> {
    embedded_name_tag_offsets
        .iter()
        .copied()
        .filter_map(|name_tag_relative_offset| {
            let prefix_payload = records_payload.get(..name_tag_relative_offset)?;
            if prefix_payload.len() < 7 {
                return None;
            }
            let prefix_leading_dword = read_u32_at(prefix_payload, prefix_payload.len() - 7)?;
            let prefix_trailing_word = read_u16_at(prefix_payload, prefix_payload.len() - 3)?;
            let prefix_separator_byte = *prefix_payload.last()?;
            let mut parsed_names = None;
            for relative_name_offset in [4usize, 6usize] {
                let Some(name_payload) =
                    records_payload.get(name_tag_relative_offset + relative_name_offset..)
                else {
                    continue;
                };
                if let Some((names, name_payload_len)) =
                    parse_save_len_prefixed_ascii_name_triplet_and_consumed_len(name_payload)
                {
                    parsed_names = Some((relative_name_offset, name_payload_len, names));
                    break;
                }
            }
            let (name_payload_relative_offset, name_payload_len, names) =
                parsed_names.unwrap_or((4usize, 0usize, Default::default()));
            let (primary_name, secondary_name, tertiary_name) = names;
            Some(EmbeddedNameRow {
                name_tag_relative_offset,
                prefix_leading_dword,
                prefix_trailing_word,
                prefix_separator_byte,
                name_payload_relative_offset,
                name_payload_len,
                primary_name: (!primary_name.is_empty()).then_some(primary_name),
                secondary_name: (!secondary_name.is_empty()).then_some(secondary_name),
                tertiary_name,
            })
        })
        .collect()
}
