/** 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/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()->unregisterScenarioObjects();

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

	CSGXAudioEngine::get()->unregisterScenarioObjects();
	CSGXGraphicsEngine::get()->unregisterScenarioObject(m_pWorldObject);
	CSGXGameEngine::get()->unregisterScenarioObject(m_pWorldObject);

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

	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()->releaseScenarioObjects();

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

	m_pReplacementScenario = NULL;

	return success;
}

