#include <irrlicht.h>
#include <IPhysics.h>

#pragma comment(lib, "Irrlicht.lib")
#pragma comment (lib, "IPhysics.lib")

using namespace irr;
using namespace video;
using namespace scene;
using namespace core;

CPhysicsCamera* camera;

class eventReceiver : public IEventReceiver
{
public:
	eventReceiver() {}
	~eventReceiver() {}
	
	bool OnEvent(SEvent event)
	{
		camera->onEvent(event);

		return false;
	}

};

int main()
{
	IrrlichtDevice* device = createDevice(EDT_OPENGL);

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

	CPhysics physics;
	physics.init(device);
	physics.setUpdateMode(UM_EVERY_FRAME);
	physics.setPlatformArchitecture(EPA_BEST);

	//Create Level Collision
	device->getFileSystem()->addZipFileArchive("../../Media/map-20kdm2.pk3");

 	IAnimatedMesh* levelmesh = smgr->getMesh("20kdm2.bsp");
	IAnimatedMeshSceneNode* levelnode = smgr->addAnimatedMeshSceneNode(levelmesh);

	SPhysicsStaticMesh level;
	level.mesh = levelmesh;
	level.node = levelnode;
	level.scale = vector3df(1, 1, 1);
	level.node->setScale(level.scale);

	IPhysicsEntity* levelEntity = physics.addEntity(&level);
	levelEntity->setPosition(vector3df(-1300,-144,-1249)*level.scale);	

	//Create camera
	SPhysicsCamera cam;
	cam.node = smgr->addCameraSceneNode();
	cam.bodySize = vector3df(35, 42, 35);
	cam.mass = 10.0f;
	cam.moveSpeed = 5.0f;
	cam.sensitivity = 100.0f;

	camera = physics.addCamera(&cam);
	camera->setPosition(vector3df(10,5,10));

	SCameraKeyMap* km = new SCameraKeyMap;
	km[0].key = KEY_KEY_W;
	km[0].action = EA_MOVE_FORWARD;
	km[1].key = KEY_KEY_S;
	km[1].action = EA_MOVE_BACKWARD;
	km[2].key = KEY_KEY_A;
	km[2].action = EA_STRAFE_LEFT;
	km[3].key = KEY_KEY_D;
	km[3].action = EA_STRAFE_RIGHT;

	camera->setKeyMap(km,4);

	eventReceiver receiver;
	device->setEventReceiver(&receiver);

	while (device->run())
	{
		if (device->isWindowActive())
		{
			driver->beginScene(true, true, SColor(255,0,0,0));

			smgr->drawAll();

			physics.update();

			driver->endScene();
		}
	}
	
	physics.close();

	return 0;
}
