#include "client/audio/AudioLoader.h"

#include "blitz/misc/Log.h"
#include "client/AssetsManager.h"

namespace blitz {
namespace audio {

namespace AudioLoader {

struct WavHeader {
	/* RIFF Chunk Descriptor */
	uint8_t RIFF[4];	 // RIFF Header Magic header
	uint32_t ChunkSize;	 // RIFF Chunk Size
	uint8_t WAVE[4];	 // WAVE Header
	/* "fmt" sub-chunk */
	uint8_t FMT[4];			 // FMT header
	uint32_t Subchunk1Size;	 // Size of the fmt chunk
	uint16_t AudioFormat;	 // Audio format 1=PCM,6=mulaw,7=alaw,     257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
	uint16_t NumOfChan;		 // Number of channels 1=Mono 2=Sterio
	uint32_t SamplesPerSec;	 // Sampling Frequency in Hz
	uint32_t BytesPerSec;	 // bytes per second
	uint16_t BlockAlign;	 // 2=16-bit mono, 4=16-bit stereo
	uint16_t BitsPerSample;	 // Number of bits per sample
	/* "data" sub-chunk */
	uint8_t Subchunk2ID[4];	 // "data"  string
	uint32_t Subchunk2Size;	 // Sampled data length
};

AudioData LoadAudioFile(const std::string& filePath) {

	DataBuffer fileBuffer = utils::AssetsManager::GetAsset(filePath);

	WavHeader wavHeader;
	fileBuffer >> wavHeader;

	if (wavHeader.Subchunk2Size == 0) {
		utils::LOGE("[AudioLoader] Failed to load sound " + filePath + " !");
	}

	fileBuffer.Resize(fileBuffer.GetReadOffset() + wavHeader.Subchunk2Size);

	int audioFormat = (wavHeader.NumOfChan - 1) * 2 + (wavHeader.BitsPerSample / 8) - 1;

	return {fileBuffer, AudioFormat(audioFormat), wavHeader.SamplesPerSec};
}

};	// namespace AudioLoader

}  // namespace audio
}  // namespace blitz