
#include <stdio.h>
#include <stdlib.h>

#include "cgSound.h"

namespace engine
{

	cgSound::cgSound()
	{

	}

	cgSound::~cgSound()
	{
		if ( music )
			musicUnload();

		if ( initialized )
			finalize();
	}

	void cgSound::initialize(int frequency, int streams, unsigned int flags)
	{
	    if (FSOUND_GetVersion() < FMOD_VERSION)
		{
			printf("Error : You are using the wrong DLL version!  You should be using FMOD %.02f\n", FMOD_VERSION);
			exit(1);
		}

		if ( !FSOUND_Init(frequency, streams, flags) )
		{
			printf("%s\n", FMOD_ErrorString(FSOUND_GetError()));
			exit(1);
		}

		initialized = true;
	}

	void cgSound::finalize()
	{
		if ( !initialized )
			return;

		FSOUND_Close();
	}

	void cgSound::musicLoad(const char* filename, unsigned int mode, int offset, int length)
	{
		if ( music )
			musicUnload();

		music = FSOUND_Stream_Open(filename, mode, offset, length);

		if ( !music )
		{
			printf("%s\n", FMOD_ErrorString(FSOUND_GetError()));
			exit(1);
		}

	}

	void cgSound::musicPlay()
	{
		if ( !music )
			return;

		FSOUND_Stream_Play(0, music);
	}

	void cgSound::musicPause()
	{
		if ( !music )
			return;

		//FSOUND_Stream_Pause(0, music);
	}

	void cgSound::musicStop()
	{
		if ( !music )
			return;

		FSOUND_Stream_Stop(music);
	}

	void cgSound::musicUnload()
	{
		if ( !music )
			return;

		FSOUND_Stream_Close(music);

		music = NULL;
	}

	void cgSound::musicVolume(char volume)
	{
		FSOUND_SetVolume(0, (int)volume);
	}



	void cgSound::soundPrecache(int id, const char* filename, unsigned int mode, int offset, int length)
	{
		sound[id] = FSOUND_Sample_Load(id, filename, mode | FSOUND_LOOP_OFF, offset, length);

		if ( !sound )
		{
			printf("%s\n", FMOD_ErrorString(FSOUND_GetError()));
			exit(1);
		}
	}

	void cgSound::soundPlay(int id)
	{
		FSOUND_PlaySound(1, sound[id]);
	}

	void cgSound::soundPause()
	{
		//FSOUND_PlaySound(0, sound);
	}

	void cgSound::soundStop()
	{
		FSOUND_StopSound(1);
	}

	void cgSound::soundUnload(int id)
	{
		FSOUND_Sample_Free(sound[id]);
	}
}