A rust port of vgm2mid by Paul Jensen and Valley Bell
use crate::{strict, verbose};
use anyhow::{bail, Result};
use utf16string::{WString, LE};

#[allow(dead_code)]
pub(crate) struct Gd3Header {
	str_gd3: [u8; 4],
	version: u32,
	tag_length: u32,
	track_name_e: WString<LE>,
	track_name_j: WString<LE>,
	game_name_e: WString<LE>,
	game_name_j: WString<LE>,
	system_name_e: WString<LE>,
	system_name_j: WString<LE>,
	author_name_e: WString<LE>,
	author_name_j: WString<LE>,
	release_date: WString<LE>,
	creator: WString<LE>,
	notes: WString<LE>,
}

pub(crate) fn get_gd3_header(opt_data: Option<&[u8]>) -> Result<Gd3Header> {
	let mut gd3_header = Gd3Header {
		str_gd3: [0; 4],
		version: 0,
		tag_length: 0,
		track_name_e: "".into(),
		track_name_j: "".into(),
		game_name_e: "".into(),
		game_name_j: "".into(),
		system_name_e: "".into(),
		system_name_j: "".into(),
		author_name_e: "".into(),
		author_name_j: "".into(),
		release_date: "".into(),
		creator: "".into(),
		notes: "".into(),
	};

	let data = match opt_data {
		Some(d) => d,
		None => {
			return Ok(gd3_header);
		},
	};

	if data.len() <= 0x22 {
		// 4 x 3 + 2 x 11
		bail!("GD3 data is too small.");
	}

	let mut _cur_pos = 0;
	gd3_header.str_gd3.clone_from_slice(&data[0..3]);

	if gd3_header.str_gd3 != "gd3 ".as_bytes() {
		verbose!("Invalid GD3 header.");
		strict!();
	}

	gd3_header.version = u32::from_le_bytes(data[4..7].try_into()?);
	gd3_header.tag_length = u32::from_le_bytes(data[8..11].try_into()?);

	//gd3_header.track_name_e = WString::from_utf16(data.chunks(2).take_while(|&slice| slice != [0, 0]).copied().collect())?;

	Ok(gd3_header)
}