#include "CDAudioManager.h"
#include "CDAudioSound.h"

extern HWND      main_window_handle;

//----------------------------------------------------------------//
//	Constructor/Deconstructor
//----------------------------------------------------------------//	

CDAudioManager::CDAudioManager()
{
	m_Performance = NULL;
	m_Loader	  = NULL;


}

CDAudioManager::~CDAudioManager()
{


}

bool CDAudioManager::Init()
{

	CoInitialize(NULL);

	
	
	CoCreateInstance(CLSID_DirectMusicLoader, NULL, CLSCTX_INPROC, IID_IDirectMusicLoader8, (void**) &m_Loader);

	CoCreateInstance(CLSID_DirectMusicPerformance, NULL, CLSCTX_INPROC, IID_IDirectMusicPerformance8, (void**) &m_Performance);	

	m_Performance->InitAudio(NULL,										// no interface needed
							NULL,										// no interface needed
							main_window_handle,							// handle to the window
							DMUS_APATH_SHARED_STEREOPLUSREVERB,		    // default audiopath
							64,											// 64 channels allocated to the audiopath
							DMUS_AUDIOF_ALL,							// allow all synthesizer features
							NULL);										// default audio parameters

	

	//Setup the load segment

	char searchPath[MAX_PATH];
	WCHAR wSearchPath[MAX_PATH];

	GetCurrentDirectory(MAX_PATH, searchPath);
	MultiByteToWideChar(CP_ACP, 0, searchPath, -1, wSearchPath, MAX_PATH);

	m_Loader->SetSearchDirectory(GUID_DirectMusicAllTypes, wSearchPath, FALSE);





	
	return true;
}

bool CDAudioManager::Shutdown()
{
	m_Performance->CloseDown();
	m_Loader->Release();
	m_Performance->Release();

	CoUninitialize();


	return true;
}


//----------------------------------------------------------------//
//	Playing/Loading Sounds
//----------------------------------------------------------------//	

CSound* CDAudioManager::LoadCSound(STRINGC fileName)
{

	CDAudioSound* sound= new CDAudioSound();
	sound->Init(fileName);

	char filename[MAX_PATH] = "test.wav";
	WCHAR wFilename[MAX_PATH];

	MultiByteToWideChar(CP_ACP, 0, fileName.GetString(), -1, wFilename, MAX_PATH);

	if(FAILED(m_Loader->LoadObjectFromFile(CLSID_DirectMusicSegment,
									IID_IDirectMusicSegment8,
									wFilename,
									(void**) &(sound->m_Segment))))
	{
		Assert(false, STRINGC("Could not load sound file: ") + fileName);

	}

	//m_Performance->Download(sound->getSegment())

	sound->getSegment()->Download(m_Performance);



	return (CSound*)sound;

}


void CDAudioManager::PlayCSound(CSound* sound, bool loop=false)
{

	CDAudioSound* DAsound = (CDAudioSound*) sound;

	

	if(loop)
	{
		DAsound->getSegment()->SetRepeats(DMUS_SEG_REPEAT_INFINITE);
		
	}

	m_Performance->PlaySegmentEx(DAsound->getSegment(), NULL, NULL, 0, 0, NULL, NULL, NULL);

	
}

