use super::super::super::*;
use super::super::embedded_names::EmbeddedNameRow;
use super::super::payload_envelope::PayloadEnvelopeRow;

pub(super) type NamePreludeCandidateRow = (
    usize,
    Option<String>,
    Option<String>,
    u32,
    u16,
    u8,
    u16,
    u8,
    Option<usize>,
    Option<(u8, u8)>,
);

pub(super) fn build_name_prelude_candidate_rows(
    records_payload: &[u8],
    payload_envelope_rows: &[PayloadEnvelopeRow],
    embedded_name_rows: &[EmbeddedNameRow],
) -> Vec<NamePreludeCandidateRow> {
    embedded_name_rows
        .iter()
        .enumerate()
        .filter_map(|(row_index, row)| {
            let candidate_offset = row.name_tag_relative_offset.checked_sub(3)?;
            let child_count_candidate = read_u16_at(records_payload, candidate_offset)?;
            let saved_primary_child_byte_candidate =
                read_u8_at(records_payload, candidate_offset + 2)?;
            Some((
                row.name_tag_relative_offset,
                row.primary_name.clone(),
                row.secondary_name.clone(),
                row.prefix_leading_dword,
                row.prefix_trailing_word,
                row.prefix_separator_byte,
                child_count_candidate,
                saved_primary_child_byte_candidate,
                row_index.checked_sub(1).and_then(|previous_index| {
                    payload_envelope_rows
                        .get(previous_index)
                        .and_then(|row| row.profile_chunk_len_to_next_name_or_end)
                }),
                row_index.checked_sub(1).and_then(|previous_index| {
                    payload_envelope_rows.get(previous_index).and_then(|row| {
                        row.short_profile_first_flag_byte
                            .zip(row.short_profile_second_flag_byte)
                    })
                }),
            ))
        })
        .collect()
}
