#include <irrlicht.h>
#include <time.h>
#include <stdio.h>
#include "globals.h"

const int FPS = 60;

IrrlichtDevice* device;

using namespace irr;

using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

#include "world.h"

int main()
{
	device = createDevice(EDT_OPENGL, dimension2d<u32>(800, 600), 32,
			false, false, true, NULL);

	device->setWindowCaption(L"Island Repair Man");

	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();

	ICameraSceneNode* camera = smgr->addCameraSceneNode(0,
		vector3df((f32)SCREEN_WIDTH/2, (f32)SCREEN_HEIGHT/2, -20),
		vector3df((f32)SCREEN_WIDTH/2, (f32)SCREEN_HEIGHT/2, 0));
	matrix4 projectionMatrix;
	projectionMatrix.buildProjectionMatrixOrthoLH((f32)SCREEN_WIDTH, (f32)SCREEN_HEIGHT, -100.f, 100.f);
	camera->setProjectionMatrix(projectionMatrix, true);

	{
		World world(smgr);
		device->setEventReceiver(&world);

		// Title screen
		gui::IGUIFont* font = device->getGUIEnvironment()->getBuiltInFont();
		video::ITexture* blurb1 = driver->getTexture("../data/img/blurb1.png");
		video::ITexture* blurb2 = driver->getTexture("../data/img/blurb2.png");
		while (device->run() && !world.clicked)
		{
			driver->beginScene(true, true, SColor(255,0,0,0));

			driver->draw2DImage(blurb1, core::position2di(0, 0));
			//driver->draw2DImage(title1, core::position2di(400, 0));
			driver->draw2DImage(blurb2, core::position2di(400, 300));
			font->draw(L"Click to start", core::recti(0, 500, 400, 550), video::SColor(255, 64, 64, 192), true, true);

			driver->endScene();
		}
		world.clicked = false;
		world.play = true;

		// Main game
		time_t startTime = clock(), endTime;
		while (device->run())
		{
			driver->beginScene(true, true, SColor(255,0,0,0));

			smgr->drawAll();
			guienv->drawAll();
			world.drawUI();

			driver->endScene();

			do
			{
				device->sleep(100 / FPS);
				endTime = clock();
			} while (endTime - startTime < CLOCKS_PER_SEC / FPS);

			world.update(1.0f / FPS);
			printf("%d ms / frame\n", 1000*(endTime - startTime) / CLOCKS_PER_SEC);
			startTime = endTime;
		}
	} // destruct world

	device->drop();
	return 0;
}