#include "SoundManager.h"

SoundManager::SoundManager(void)
{
	currentAvailableIndex = 1;
	playing = -1;
	FSOUND_SetOutput( FSOUND_OUTPUT_DSOUND );

	/* internal memory management - give it 1 mb and no more mallocs will come from fmod */
    if (!FSOUND_SetMemorySystem(malloc(4*1024*1024), 4*1024*1024, NULL, NULL, NULL)) 
    {
        GameError( "Could not load fmod sound library" );
    }

	// Set the sound driver
	FSOUND_SetDriver( 0 );       /* Select sound card (0 = default) */

	// Initialize fmod
    if (!FSOUND_Init(44100, 32, FSOUND_INIT_USEDEFAULTMIDISYNTH))
    {
        GameError( "Could not load fmod sound library" );
    }
}

SoundManager::~SoundManager(void)
{
	// Loop over the sounds killing them
	for ( SoundMapIterator iter = sounds.begin();
			iter != sounds.end();
			iter++ ) {
			FSOUND_SAMPLE* aSound = ( FSOUND_SAMPLE* ) ( *iter ).second;
			FSOUND_Sample_Free( aSound );
	}

	FSOUND_Close();
}

int SoundManager::loadSound( char* fileName ) {
	/* PCM,44,100 Hz, 8 Bit, Mono */
    FSOUND_SAMPLE* aSample = FSOUND_Sample_Load( FSOUND_UNMANAGED, fileName, FSOUND_NORMAL | FSOUND_HW2D, 0, 0);   /* hardware? why not, just to show it can be done */
    if ( !aSample ) {
        GameError( "Error loading sound file." );
		return -1;
    }

	// Add it to our map
	sounds[ currentAvailableIndex ] = aSample;
	currentAvailableIndex++;

	return currentAvailableIndex - 1;
}

HRESULT SoundManager::playSound( int whichSound, bool looping ) {
	if ( looping ) {
		FSOUND_Sample_SetMode( sounds[ whichSound ], FSOUND_LOOP_NORMAL);
	} else {
		FSOUND_Sample_SetMode( sounds[ whichSound ], FSOUND_LOOP_OFF);
		FSOUND_Sample_SetMaxPlaybacks( sounds[ whichSound ], 1 );
	}

	// Actually play the song
	playing = FSOUND_PlaySound( FSOUND_FREE, sounds[ whichSound ] );

	if ( playing == -1 ) {
		return E_FAIL;
	}

	return S_OK;
}

void SoundManager::unloadSound( int whichSound ) {
	FSOUND_Sample_Free( sounds[ whichSound ] );
}

HRESULT SoundManager::loadSoundFromFile( char* filename ) {
	HRESULT r = S_OK;

	fstream soundFile( filename );
	char name[ 128 ];

	GameError( filename );
	while ( soundFile.peek() != -1 ) {
		soundFile >> name; 
		if ( name != NULL ) {
			loadSound( name );
		} else {
			GameError( "Problems while loading sound file" );
			return E_FAIL;
		}
	}

	soundFile.close();

	return r;
}

void SoundManager::stopCurrentBackground() {
	stopMusic( playing );
}

void SoundManager::stopMusic( int whichSound ) {
	FSOUND_StopSound( whichSound );
}

HRESULT SoundManager::playSoundFX( int whichSound ) {
	// Actually play the fx
	int play = FSOUND_PlaySound( FSOUND_FREE, sounds[ whichSound ] );

	if ( play == -1 ) {
		return E_FAIL;
	}

	return S_OK;
}
