/*  $Id: setupsdl.cpp,v 1.8 2004/03/13 23:04:13 mbn 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 "API/SDL/setupsdl.h"
#include "API/Core/System/error.h"
#include <SDL/SDL.h>
#include "sdl_target.h"

/////////////////////////////////////////////////////////////////////////////
// CL_SetupSDL construction:

static CL_SDLTarget *target = 0;

static int ref_count = 0;

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

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

void CL_SetupSDL::init(bool register_resources_only)
{
	ref_count++;
	if (ref_count != 1) return;

	if (register_resources_only) return;

	// Lawouach : I guess an error here is supposed to throw a CL_Error ?
	// BTW, it seems that SDL_INIT_AUDIO component has to be initiliazed before the display window under DirectX (well SDL is still based on DX 5 !!)
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) < 0)
		throw CL_Error(SDL_GetError());

	// Enable unicode support in keyboard events:
	// Lawouach : This slows down the performances
	SDL_EnableUNICODE(1);

	// Enable key repeat
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,SDL_DEFAULT_REPEAT_INTERVAL);

	target = new CL_SDLTarget;
}
	
void CL_SetupSDL::deinit()
{
	ref_count--;
	if (ref_count != 0) return;

	if(target)
		delete target;
	target = 0;

	// Lawouach : when we quit SDL_VIDEO subsystem we don't need to explictely free the display pointer though it wouldn't hurt
	SDL_Quit();
}
