/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     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: src/sgx/game/scenario.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/game/game.hpp"
#include "sgx/graphics/graphics.hpp"
#include "sgx/gui/gui.hpp"
#include "sgx/audio/audio.hpp"

CSGXScenarioManager *CSGXScenarioManager::m_pSingleton = NULL;
   
//
//
//
CSGXGameScenario::~CSGXGameScenario() {
	release();
}

tBOOL CSGXGameScenario::release() {
	CSGXGUI::get()->setRootWidget(NULL);
	CSGXGUI::get()->unregisterObjects();

	CSGXAudioEngine::get()->stopAllSounds(NULL);

	CSGXAudioEngine::get()->unregisterObjects();
	CSGXGraphicsEngine::get()->unregisterObject(m_pWorldObject);
	CSGXGameEngine::get()->unregisterObject(m_pWorldObject);

	CSGXGraphicsEngine::get()->unregisterObjects();
	CSGXGameEngine::get()->unregisterObjects();

	delete m_pWorldObject;

	return TRUE;
}

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

CSGXScenarioManager *CSGXScenarioManager::get()
{
	if (!m_pSingleton) {
		return create();
	}
	return m_pSingleton;
}

void

CSGXScenarioManager::initialize() 
{
	m_pCurrentScenario = NULL;
	m_pReplacementScenario = NULL;
}

void
CSGXScenarioManager::cueNextScenario(CSGXGameScenario *pScenario, tMEM_SIZE userdata) {
	m_pReplacementScenario = pScenario;
	m_ReplacementUserdata = userdata;
}

tBOOL
CSGXScenarioManager::hasScenarioChanged() 
{
	return m_pReplacementScenario != NULL;
}

tBOOL
CSGXScenarioManager::switchScenario() 
{
	if (!hasScenarioChanged()) {
		return FALSE;
	}
	//
	tBOOL success = FALSE;

	if (m_pCurrentScenario) {
		m_pCurrentScenario->release();
		m_pCurrentScenario = NULL;
	}

	CSGXHappening::get()->unregisterScenarioObjectsFromAllEngines();
	CSGXManagementEngine::get()->releaseGameObjects();

	if (m_pReplacementScenario) {
		success = m_pReplacementScenario->create(m_ReplacementUserdata);
		if (success) {
			m_pCurrentScenario = m_pReplacementScenario;
		}
	}

	m_pReplacementScenario = NULL;

	return success;
}

