#include "stdafx.h"
#include "Jukebox.h"
#include "Utilities.h"
#include "resource.h"



using namespace std;



CJukebox::CJukebox( const HINSTANCE& hInstance )
: m_bInitialized( false )
{
	for( int i( 0 ); i < NUM_SOUNDS; ++i )
	{
		m_soundStreams[ i ].str = 0;
		m_soundStreams[ i ].mem = 0;
	}

	// initialize sound system
	assert( CS_GetVersion() == CS_VERSION );
	CS_SetOutput( CS_OUTPUT_DSOUND ); // WaveOut should be available on pretty much all machines and Windows versions
	if( 0 != CS_Init( 44100, NUM_SOUNDS, 0 ) )
	{
		m_bInitialized = true;
	}

	// open all streams
	OpenStream( hInstance, SND_BACKGROUND_MUSIC, CS_LOOP_NORMAL );
	OpenStream( hInstance, SND_BUTTON_HOVERING, CS_LOOP_OFF );
	OpenStream( hInstance, SND_BUTTON_PRESSED, CS_LOOP_OFF );
}



CJukebox::~CJukebox()
{
	ShutDown();
}



void 
CJukebox::PlaySound( ESounds eSoundID )
{
	if( false != m_bInitialized && 0 != m_soundStreams[ eSoundID ].str )
	{
		// stop stream if currently playing
		CS_Stream_Stop( m_soundStreams[ eSoundID ].str );
		// start playing stream on assigned channel
		CS_Stream_Play( eSoundID, m_soundStreams[ eSoundID ].str );
	}
}



//void 
//CJukebox::SetVolume( unsigned char ucVolume )
//{
//	if( false != m_bInitialized )
//	{
//		// set volume of all channels
//		CS_SetVolume( CS_ALL, ucVolume );
//	}
//}



void 
CJukebox::OpenStream( const HINSTANCE& hInstance, ESounds eSoundID, unsigned int uiPlayMode )
{
	if( false != m_bInitialized )
	{
		assert( 0 == m_soundStreams[ eSoundID ].str );
		assert( 0 == m_soundStreams[ eSoundID ].mem );

		// resource ID names for sound IDs... 
		// it's crucial that the order matches the one defined in ESounds
		const TCHAR* c_pcSoundResNames[ NUM_SOUNDS ] =
		{
			_T( "IDR_SND_BACKGROUND_MUSIC" ),
			_T( "IDR_SND_BUTTON_HOVERING" ),
			_T( "IDR_SND_BUTTON_LEFTUNTOUCHED" ),
			_T( "IDR_SND_BUTTON_PRESSED" ),
			_T( "IDR_SND_BUTTON_RELEASED" )
		};

		// get access to sound in resource
		const unsigned char* pucSoundData( 0 );
		unsigned int uiSoundDataSize( 0 );
		GetAccessToResource( pucSoundData, uiSoundDataSize, c_pcSoundResNames[ eSoundID ] );

		if (pucSoundData)
		{
			m_soundStreams[eSoundID].mem = new char[uiSoundDataSize];
			if (m_soundStreams[eSoundID].mem)
			{
				memcpy(m_soundStreams[eSoundID].mem, pucSoundData, uiSoundDataSize);

				// open sound stream (returns NULL if sound couldn't be opened)
				m_soundStreams[ eSoundID ].str = CS_Stream_OpenFile( m_soundStreams[eSoundID].mem, CS_LOADMEMORY | uiPlayMode, uiSoundDataSize );
			}
		}
	}
}



void
CJukebox::ShutDown()
{
	// stop all streams and close them
	for( int i( 0 ); i < NUM_SOUNDS; ++i )
	{
		if( 0 != m_soundStreams[ i ].str )
		{
			CS_Stream_Stop( m_soundStreams[ i ].str );
			CS_Stream_Close( m_soundStreams[ i ].str );
		}

		if (m_soundStreams[i].mem)
		{
			delete [] m_soundStreams[i].mem;
			m_soundStreams[i].mem = 0;
		}
	}

	// shut down sound system
	CS_Close();
}
