//	SDL2.0Thread.h - A Thread implementation based on SDL 2.0.
//  ----------------------------------------------------------------------------
//	This file is part of 'NiallsAVLib', base code for any kind of audiovisual
//	apps.
//	Copyright (C) 2012  Niall Moody
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	This program 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 General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//	----------------------------------------------------------------------------

#include "SDL2.0Thread.h"
#include "DebugHeaders.h"

#include "SDL_thread.h"
#include "SDL_timer.h"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
SDL2_0Thread::SDL2_0Creator SDL2_0Thread::creator;

//------------------------------------------------------------------------------
SDL2_0Thread::SDL2_0Thread():
thread(0)
{

}

//------------------------------------------------------------------------------
SDL2_0Thread::~SDL2_0Thread()
{
	//Just in case.
	if(thread)
		waitToFinish();
}

//------------------------------------------------------------------------------
bool SDL2_0Thread::createThread(ThreadMethod threadMethod,
							    const std::string& name,
							    void *data)
{
	if(!thread)
	{
		thread = SDL_CreateThread(threadMethod,
								  name.c_str(),
								  static_cast<void *>(data));
		if(!thread)
			DebugStatement(L"SDL1.2Thread: Could not create thread.");
	}

	return (thread != 0);
}

//------------------------------------------------------------------------------
void SDL2_0Thread::waitToFinish()
{
	if(thread)
	{
		SDL_WaitThread(thread, NULL);
		thread = 0;
	}
	else
		DebugStatement(L"SDL1.2Thread: Calling waitToFinish() on a non-existent thread.");
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void SDL2_0Thread::SDL2_0Creator::wait(int milliseconds) const
{
	SDL_Delay(milliseconds);
}
