use anyhow::Result;
use byteorder::{LittleEndian, ReadBytesExt};
use std::collections::HashMap;
use std::io::{BufReader, Read};
use std::path::Path;

/// Read cliloc.enu and return a map from string ID to localized string.
pub fn read_cliloc(path: &Path) -> Result<HashMap<u32, String>> {
    let file = std::fs::File::open(path)?;
    let mut reader = BufReader::new(file);

    // Header: u32 unknown, u16 unknown
    let _header1 = reader.read_u32::<LittleEndian>()?;
    let _header2 = reader.read_u16::<LittleEndian>()?;

    let mut map = HashMap::new();

    loop {
        let id = match reader.read_u32::<LittleEndian>() {
            Ok(v) => v,
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
            Err(e) => return Err(e.into()),
        };
        let _flag = reader.read_u8()?;
        let length = reader.read_u16::<LittleEndian>()?;

        let mut text_buf = vec![0u8; length as usize];
        reader.read_exact(&mut text_buf)?;
        let text = String::from_utf8_lossy(&text_buf).to_string();
        map.insert(id, text);
    }

    Ok(map)
}
