//! Wad file entry type.

use crate::durandal::{bin::usize_from_u32, err::*};
use super::chnk;
use std::collections::BTreeMap;

/// Reads all entries in a `Wad`.
pub fn read(b: &[u8],
            old_wad: bool,
            old_dat: bool,
            siz_app: usize,
            siz_ent: usize,
            siz_cnk: usize)
   -> ResultS<EntryMap>
{
   read_data! {
      endian: BIG, buf: b, size: 128, start: 0, data {
         let dirofs  = u32[72] usize;
         let numents = u16[76] usize;
      }
   }

   let mut entries = EntryMap::new();
   let mut p = dirofs;

   for i in 0..numents {
      read_data! {
         endian: BIG, buf: b, size: siz_ent, start: p, data {
            let offset = u32[0] usize;
            let size   = u32[4] usize;
            let index  = u16[8];
         }
      }

      let index = if old_wad {i as u16} else {index};

      let chunks  = chnk::read(&b[offset..offset + size], old_dat, siz_cnk)?;
      let appdata = b[p..p + siz_app].to_vec();

      entries.insert(index, Entry{chunks, appdata});

      p += siz_ent + siz_app;
   }

   Ok(entries)
}

/// An entry containing chunks and application-specific data.
#[cfg_attr(feature = "serde_obj", derive(serde::Serialize))]
#[derive(Debug, Eq, PartialEq)]
pub struct Entry
{
   /// All of the chunks in this `Entry`.
   pub chunks: Vec<chnk::Chunk>,

   /// The application specific data for this Entry.
   pub appdata: Vec<u8>,
}

/// A map of indexed entries.
pub type EntryMap = BTreeMap<u16, Entry>;

// EOF
