#include "Salamander.h"
#include "Platform.h"

#include "Body.h"
#include "Polygon.h"
#include "World.h"

#include <sstream>

Platform::Platform(std::string filename) : Body()
{
	load(filename);
}

Platform::~Platform()
{
	
}

void Platform::frame()
{
	
}

void Platform::load(std::string filename)
{
	// stuff
	std::string texturename;
	unsigned int texturesize = 0;
	unsigned int vertexcount = 0;
	double mass = 0.0;

	// load from a file
	std::string line;
	std::ifstream file ("..\\data\\" + filename);
	
	// texture name
	std::getline(file, texturename);

	// texture size
	std::getline(file, line);
	std::istringstream texturesizess(line);
	texturesizess >> texturesize;

	// mass
	std::getline(file, line);
	std::istringstream masss(line);
	masss >> mass;

	// number of vertices
	std::getline(file, line);
	std::istringstream vertexcountss(line);
	vertexcountss >> vertexcount;

	// read the vertices
	Polygon* polygon = new Polygon();
	for(unsigned int i = 0; i < vertexcount; i++)
	{
		Vec2 v;
		std::getline(file, line);

		std::string x = line.substr(0, line.find(", "));
		std::istringstream xss(x);
		xss >> v.x_;

		std::string y = line.substr(line.find(", ") + 2);
		std::istringstream yss(y);
		yss >> v.y_;

		polygon->addVertex(v);
	}

	// done
	file.close();

	
	// finish loading the physics stuff
	setShape(polygon);
	setMass(mass);
	angularVelocity_ = (rand() % 1000 - 500) * 0.001;

	// and the graphics stuff
	sprite_ = new Sprite();
	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_->setColour(Colour(1.0, 1.0, 1.0, 1.0));
	sprite_->setTexture(asset().load<Texture>("..\\data\\" + texturename));
	sprite_->setReferenceFrame(Entity::WORLD);
	sprite_->setScale(Vec2(texturesize, texturesize));
	scene().addChild(*sprite_);

}

void Platform::propogate()
{
	// First update the base class properties.
	Body::propogate();

	// Then update our geometry transform.
	sprite_->setTranslation(getTranslation());
	sprite_->setRotation(getRotation());
}

void Platform::updateMatrix()
{
	// first we hitch a ride on this with the frame
	frame();

	// then update
	Body::updateMatrix();
}