#include "testcommon/testcommon.h"
#include "spcore/coreruntime.h"
#include "mod_sdl/sdlsurfacetype.h"
#include <boost/thread.hpp>
#include <stdlib.h>

using namespace spcore;
using namespace mod_sdl;

static int TestCreation()
{
	SmartPtr<IComponent> compo= getSpCoreRuntime()->CreateComponent ("sdl_drawer", "my_drawer", 0, NULL);
	if (!compo.get())  ExitErr ("error creating sdl_drawer");
	compo->Initialize();

	if (compo->Initialize()) ExitErr ("A second Initialize should work");
	SLEEP(2);

	SmartPtr<IComponent> compo2= getSpCoreRuntime()->CreateComponent ("sdl_drawer", "my_drawer2", 0, NULL);
	if (compo2.get()) ExitErr ("error 2nd sdl_drawer creation allowed");
	compo->Finish();

	return 0;
}

static void TestSimpleDraw ()
{
	// Create a drawer component
	SmartPtr<IComponent> compo= getSpCoreRuntime()->CreateComponent ("sdl_drawer", "my_drawer", 0, NULL);
	if (!compo.get()) ExitErr ("TestSimpleDraw: error creating sdl_drawer");
	compo->Initialize();

	const SDL_VideoInfo* vi= SDL_GetVideoInfo();
	if (!vi) ExitErr ("SDL_GetVideoInfo() returned NULL");

	SDL_Surface* mySurface= SDL_CreateRGBSurface(SDL_HWSURFACE, 300, 400, vi->vfmt->BitsPerPixel, 0,0,0,0);
	if (mySurface== NULL) ExitErr(SDL_GetError());
	SmartPtr<CTypeSDLSurface> sur= CTypeSDLSurface::CreateInstance();
	sur->setSurface(mySurface);

	// Draw some randow shapes
	for (int i= 0; i< 10; ++i) {
		SDL_Rect rect;
		rect.x= rand() % 250;
		rect.y= rand() % 350;
		rect.w= rand() % 100;
		rect.h= rand() % 150;

		if (SDL_FillRect(mySurface, &rect, SDL_MapRGB(vi->vfmt, rand() % 256, rand() % 256, rand() % 256) ))
			ExitErr(SDL_GetError());
	}

	// Display surface
	IInputPin* drawPin= IComponent::FindInputPin(*compo, "draw");
	if (!drawPin) ExitErr("input pin 'draw' not found");
	drawPin->Send(sur);

	SLEEP(2);

	compo->Finish();
}


static void DoTests()
{
	// Initialization
	spcore::ICoreRuntime* cr= spcore::getSpCoreRuntime();
	assert (cr);

	if (cr->LoadModule ("mod_sdl")< 0) exit(-1);

	if (TestCreation()!= 0) exit (-1);

	TestSimpleDraw ();
}

int main(int argc, char *argv[]) 
{
	DoTests();

	// Cleanup
	spcore::freeSpCoreRuntime();

	return 0;
}
