#include "Morault_Map.h"
#include "Morault_EngineInfo.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <pugixml.hpp>

Morault::Maps::Map::Map()
{
}

Morault::Maps::Map::Map(std::string path)
{
}

void Morault::Maps::Map::LoadMap(std::string path)
{
	MapTriangles.clear();
	pugi::xml_document doc;
	pugi::xml_parse_result result = doc.load_file(path.c_str());
	if (result) {
		pugi::xml_node root = doc.child("shuman");
		for (const auto& triangle : root.children("triangle")) {
			MapTriangle newTri;

			newTri.a.x = std::stof(triangle.child("a").child("x").child_value());
			newTri.a.y = std::stof(triangle.child("a").child("y").child_value());
			newTri.b.x = std::stof(triangle.child("b").child("x").child_value());
			newTri.b.y = std::stof(triangle.child("b").child("y").child_value());
			newTri.c.x = std::stof(triangle.child("c").child("x").child_value());
			newTri.c.y = std::stof(triangle.child("c").child("y").child_value());

			newTri.wallAB = triangle.child("wallab").child_value();
			newTri.wallBC = triangle.child("wallbc").child_value();
			newTri.wallCA = triangle.child("wallca").child_value();

			newTri.ceilingTexture = triangle.child("ceiling").child_value();
			newTri.floorTexture = triangle.child("floor").child_value();


			newTri.heightCeiling = std::stoi(triangle.child("ceilingheight").child_value());
			newTri.heightFloor = std::stoi(triangle.child("floorheight").child_value());



			MapTriangles.push_back(newTri);
		}
	}
	else {
		throw std::runtime_error("can't open file " + path + "!\n");
	}
}

void Morault::Maps::Map::SaveMap(std::string path)
{
	std::ofstream out(path);
	out << "<!-- MANUAL OUTPUTTER -->\n\n";
	out << "<shuman>\n";
	out << "<engineinfo> <!-- For Debugging Purposes -->\n";
	out << "<engineversion>" << MORAULT_ENGINE_VERSION << "</engineversion>\n";
	out << "<enginecompiler>" << MORAULT_ENGINE_COMPILER << "</enginecompiler>\n";
	out << "</engineinfo>\n";

	for (int i = 0; i < MapTriangles.size(); i++) {
		out << "<triangle>\n";
		out << "<a><x>" << MapTriangles[i].a.x << "</x><y>" << MapTriangles[i].a.y << "</y></a>\n";
		out << "<b><x>" << MapTriangles[i].b.x << "</x><y>" << MapTriangles[i].b.y << "</y></b>\n";
		out << "<c><x>" << MapTriangles[i].c.x << "</x><y>" << MapTriangles[i].c.y << "</y></c>\n";
		out << "<wallab>" << MapTriangles[i].wallAB << "</wallab>\n";
		out << "<wallbc>" << MapTriangles[i].wallBC << "</wallbc>\n";
		out << "<wallca>" << MapTriangles[i].wallCA << "</wallca>\n";
		out << "<ceiling>" << MapTriangles[i].ceilingTexture << "</ceiling>\n";
		out << "<floor>" << MapTriangles[i].floorTexture << "</floor>\n";

		out << "<ceilingheight>" << MapTriangles[i].heightCeiling << "</ceilingheight>\n";
		out << "<floorheight>" << MapTriangles[i].heightFloor << "</floorheight>\n";
		out << "</triangle>\n";
	}

	out << "</shuman>";
	out.close();
}

Morault::Maps::Map::~Map()
{
}
