#include "Salamander.h"
#include "PhysicsMaker.h"

#include "ButtonDownEvent.h"
#include "MotionEvent.h"
#include "Line.h"
#include "Polygon.h"
#include "Platform.h"
#include "World.h"

#include <sstream>

defineUniqueId(PhysicsMaker);
PhysicsMaker::PhysicsMaker()
{
	
}

PhysicsMaker::~PhysicsMaker()
{

}

bool PhysicsMaker::startup()
{
	// DRAW CLOCKWISE!

	// Stuff to edit when creating physics things
	texturename_ = "building1_end1_1024.png";

	// physics
	polygon_ = new Polygon();

	// load an image!
	sprite_ = new Sprite();
	sprite_->setReferenceFrame(Entity::WORLD);
	sprite_->setTranslation(screen().getResolution() * 0.5);

	Stream& vcd = *(new Stream(StreamCoordinates::TypeId));
	vcd.add(*(new StreamCoordinates(0.0f, 0.0f)));
	vcd.add(*(new StreamCoordinates(1.0f, 0.0f)));
	vcd.add(*(new StreamCoordinates(0.0f, 1.0f)));
	vcd.add(*(new StreamCoordinates(1.0f, 1.0f)));
	sprite_->addStream(vcd);

	sprite_->setTexture(asset().load<Texture>("C:/Documents/C++/2011/Radia2/Game/data/" + texturename_));
	std::istringstream texturesize(texturename_.substr(texturename_.rfind("_") + 1, texturename_.rfind(".") - texturename_.rfind("_") - 1));
	texturesize >> texturesize_;
	sprite_->setScale(Vec2(texturesize_, texturesize_));
	sprite_->setColour(Colour(1.0, 1.0, 1.0, 1.0));
	scene().addChild(*sprite_);

	// events
	events().receive<PhysicsMaker, ButtonDownEvent>(this, &PhysicsMaker::onButtonDownEvent);
	events().receive<PhysicsMaker, MotionEvent>(this, &PhysicsMaker::onMotionEvent);

	return true;
}

bool PhysicsMaker::shutdown()
{
	// our own stuff
	if(polygon_)
	{
		delete polygon_;
		polygon_ = NULL;
	}
    
	return true;
}

void PhysicsMaker::frame()
{

}

void PhysicsMaker::onButtonDownEvent(const ButtonDownEvent& event)
{
	if(event.getCode() == ButtonEvent::mouseCode::Left)
	{
		// add graphics
		Sprite* corner = new Sprite();
		corner->setReferenceFrame(Entity::WORLD);
		corner->setColour(Colour(1.0, 0.0, 0.0, 1.0));
		corner->setScale(Vec2(4.0, 4.0));
		corner->setTranslation(mouse_);
		scene().addChild(*corner);

		// add to the polygon
		polygon_->addVertex(mouse_ - screen().getResolution() * 0.5);
	}
	else if(event.getCode() == ButtonEvent::keyCode::S)
	{
		// save the polygon, etc

		std::ofstream file;
		file.open ("..\\data\\" + texturename_.substr(0, texturename_.rfind(".")) + ".txt");
		
		file << texturename_ << std::endl;
		file << texturesize_ << std::endl;
		file << "1.0" << std::endl;
		file << polygon_->getNumVertices() << std::endl;
		for(unsigned int i = 0; i < polygon_->getNumVertices(); i++)
			file << polygon_->getVertex(i).x_ << ", " << polygon_->getVertex(i).y_ << std::endl;

		file.close();
	}
		
}

void PhysicsMaker::onMotionEvent(const MotionEvent& event)
{
	mouse_ = event.getMotion();
}