#include "common/stdafx.h"
#include "common/util.h"
#include "common/config-manager.h"

#include "tinsel/sound.h"
#include "tinsel/features.h"

namespace Tinsel {

Sound::Sound(Audio::Mixer *mixer) {
	uint32 numOffsets;
	const char *idxfname;
	const char *smpfname;
	Common::Language lang;

	lang = parseLanguage(ConfMan.get("language"));

	if(ConfMan.getInt("features") & GF_DW1) {
		// european versions of Discworld 1 had only english speech and
		// translated subtitles
		idxfname = "english.idx";
		smpfname = "english.smp";
	} else {
		if(lang == Common::EN_USA) {
			idxfname = "english.idx";
			smpfname = "english.smp";
		} else if(lang == Common::DE_DEU) {
			idxfname = "german.idx";
			smpfname = "german.smp";
		} else {
			error("unknown language: %s", ConfMan.get("language").c_str());
		}
	}

	_mixer = mixer;

	if(_idxfile.open(idxfname) == false)
	{
		warning("failed to open %s", idxfname);
		return;
	}

	numOffsets = _idxfile.size() / 4;
	_offsets = (uint32 *)calloc(numOffsets, sizeof(uint32));

	for(uint32 i = 0; i < numOffsets; i ++)
	{
		_offsets[i] = _idxfile.readUint32LE();
	}

	if(_smpfile.open(smpfname) == false)
	{
		warning("failed to open %s", smpfname);
		return;
	}
}

Sound::~Sound() {
}

bool Sound::playSound(uint32 index) {
	return playSoundOffset(_offsets[index]);
}

bool Sound::playSoundOffset(uint32 offset) {
	uint8 *buf;
	uint32 len;

	if(!_mixer->isReady()) {
		warning("mixer not ready");
		return false;
	}

	if(offset == 0) {
		warning("sound offset zero");
		return false;
	}

	if(!_smpfile.isOpen()) return false;

	_smpfile.seek(offset);

	if(ConfMan.getInt("features") & GF_DW1) {
		len = _smpfile.readUint32LE();

		buf = (uint8 *)calloc(len, sizeof(uint8));
		_smpfile.read(buf, len);

		debug("playing sound (offset 0x%08x, %d bytes)", offset, len);

		_mixer->playRaw(&_sfxHandle,
			buf, len, 22050,
			Audio::Mixer::FLAG_UNSIGNED | Audio::Mixer::FLAG_AUTOFREE,
			-1, 255, 0, 0, 0,
			Audio::Mixer::kSpeechSoundType);
	} // DW1
	else if(ConfMan.getInt("features") & GF_DW2) {
		// TODO
	} // DW2

	return true;
}

} // namespace Tinsel

