#include "sound/soundeffect.h"
#include "util.h"
#include <AL/al.h>

SoundEffect::SoundEffect(const std::string& filename)
{
	valid = loadFile(filename);
}

// load the whole file into a buffer, this should only be used for small sound effects. Never with music or sounds exceeding 10MB!
bool SoundEffect::loadFile(const std::string& filename)
{
	short *data;
	//std::unique_ptr<short[]> data((short*)new short[UTIL::AUDIO::CHUNK_SIZE * sizeof(short) * 2]());
	//std::vector<short> data(UTIL::AUDIO::CHUNK_SIZE * sizeof(short) * 2);
	int channels, sample_rate, samples;

	samples = stb_vorbis_decode_filename(filename.c_str(), &channels, &sample_rate, &data);
	if (samples == 0) {
		LOG(ERROR, "Failed to load sound effect '{}'", filename);
		return false;
	}
	alGenBuffers(1, &buffer);
	alBufferData(buffer, channels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16, data, samples * channels * sizeof(short), sample_rate);
	std::free(data);
	return true;
}

SoundEffect::~SoundEffect()
{
	alDeleteBuffers(1, &buffer);
}
