/*  $Id: setupcore.cpp,v 1.25 2004/04/06 12:23:56 sphair Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "Core/precomp.h"
#include <cstdlib>
#include "API/Core/Resources/resourcetype_boolean.h"
#include "API/Core/Resources/resourcetype_integer.h"
#include "API/Core/Resources/resourcetype_float.h"
#include "API/Core/Resources/resourcetype_string.h"
#include "API/Core/Resources/resourcetype_raw.h"
#include "API/Core/Resources/resource_manager.h"
#include "API/Core/System/setupcore.h"

void init_system(); // this function is implemented in init_PLATFORM.cpp
void deinit_system(); // this function is implemented in init_PLATFORM.cpp

static int ref_count = 0;
static CL_Slot slot_resource_added;

static void clancore_resource_added(CL_Resource &resource)
{
	std::string type = resource.get_type();

	if (type == "boolean") new CL_ResourceData_Boolean(resource);
	if (type == "integer") new CL_ResourceData_Integer(resource);
	if (type == "float") new CL_ResourceData_Float(resource);
	if (type == "string") new CL_ResourceData_String(resource);
	if (type == "raw") new CL_ResourceData_Raw(resource);
}

CL_SetupCore::CL_SetupCore(bool register_resources_only)
{
	CL_SetupCore::init(register_resources_only);
}

CL_SetupCore::~CL_SetupCore()
{
	CL_SetupCore::deinit();
}

void CL_SetupCore::init(bool register_resources_only)
{
	ref_count++;
	if (ref_count > 1) return;

	slot_resource_added = CL_ResourceManager::sig_resource_added().connect(&clancore_resource_added);
	if (register_resources_only) return;
	
	init_system();
}

void CL_SetupCore::deinit()
{
	// Since, CL_SetupCore::init() may be called more than once - Only call deinit at the final call to this function
	if (!ref_count) return;	// Do not allow ref_count to become negative (may occur if something calls deinit() without an init() )
	ref_count--;
	if (ref_count > 0) return;	// Wait until final call to deinit

	slot_resource_added = CL_Slot();

	deinit_system();
}
