/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/drivers/wintel32/audio/fmod/fmodsoundengine.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/filesystem/filesystem.hpp"
#include "sgx/audio/audio.hpp"

#include "drivers/wintel32/audio/fmod.hpp"

CSGXAudioEngine *CFMODSoundEngine::create()
{
	m_pSingleton = new CFMODSoundEngine();
	if (m_pSingleton) {
		m_pSingleton->initialize();
	}
	return m_pSingleton;
}

CFMODSoundEngine::~CFMODSoundEngine() {
	release();
}

void 
CFMODSoundEngine::initialize()
{
	CSGXAudioEngine::initialize();

	FMOD_System_Create(&m_System);
	FMOD_System_Init(m_System, getMaxChannels(), 0, NULL);
}


void
CFMODSoundEngine::prepareLogicalChannels(tUINT32 numChannels)
{
	CSGXAudioEngine::prepareLogicalChannels(numChannels);
	//
	m_pDeviceChannel = new CFMODDeviceChannel *[numChannels];

	for(tUINT32 i=0;i<numChannels;++i) {
		m_pDeviceChannel[i] = new CFMODDeviceChannel();
	}
}


CSampleData *
CFMODSoundEngine::createSample(const sgxString &filename, const CSGXAudioEngine::ResourceContext context/*=eDefault*/) 
{
	sgxString m_Filename = CSGXFileSystem::get()->getNativePath(filename + ".wav");
	CFMODSampleData *pSample = new CFMODSampleData(m_Filename, context, m_System);
#if 0
	if (pSample->m_pHandle == NULL) {
		delete pSample;
		return NULL;
	}
#endif
	return pSample;
}

void 
CFMODSoundEngine::updateHardwareMixer(const tREAL32 time_elapsed)
{
	for(tUINT32 i=0;i<m_NumChannels;++i) {
		if (m_pChannels[i]->m_bIsPlaying) {

			unsigned int mode = 0;
			FMOD_Channel_GetMode(m_pDeviceChannel[i]->m_pChannel, &mode);
			mode &= ~(FMOD_LOOP_OFF|FMOD_LOOP_NORMAL);
			if (m_pChannels[i]->m_pMixChannel->m_bLoop) {
				mode |= FMOD_LOOP_NORMAL;
			}
			FMOD_Channel_SetMode(m_pDeviceChannel[i]->m_pChannel, mode);
			FMOD_Channel_SetLoopCount(m_pDeviceChannel[i]->m_pChannel, m_pChannels[i]->m_pMixChannel->m_bLoop?-1:0);

			if (!m_pDeviceChannel[i]->refreshChannel(m_MixOutput[i])) {
				m_pChannels[i]->stop();
			}
		}
	}
}


void 
CFMODSoundEngine::release()
{
	FMOD_System_Close(m_System);
	FMOD_System_Release(m_System);
}

void
CFMODSoundEngine::suspendEngine()
{
}

void
CFMODSoundEngine::resumeEngine()
{
}

