#ifndef OBJECT_H
#define OBJECT_H


#include <Indoor/floorplan/v2/Floorplan.h>
#include "../gl/GLHelper.h"
#include "../gl/GLTriangles.h"
#include "../Renderable.h"

#include <KLib/data/obj/ObjectFile.h>


class Object : public Renderable {

private:

	GLTriangles<VertNormTex> triangles;

public:

	/** ctor */
	Object(const std::string& file, const std::string& colorTexture, std::string normalsTexture, const float scale = 1.0) {

		K::ObjFileReader reader(file, false);


		if (normalsTexture.empty()) {normalsTexture = ":/res/gl/tex/empty_normals.jpg";}

		triangles.setDiffuse(colorTexture.c_str());
		triangles.setNormalMap(normalsTexture.c_str());

		for (const K::ObjFileReader::Face& face : reader.getData().faces) {

			const QVector3D vertex1(face.vnt[0].vertex.x, face.vnt[0].vertex.y, face.vnt[0].vertex.z);
			const QVector3D vertex2(face.vnt[1].vertex.x, face.vnt[1].vertex.y, face.vnt[1].vertex.z);
			const QVector3D vertex3(face.vnt[2].vertex.x, face.vnt[2].vertex.y, face.vnt[2].vertex.z);

			const QVector3D normal1(face.vnt[0].normal.x, face.vnt[0].normal.y, face.vnt[0].normal.z);
			const QVector3D normal2(face.vnt[1].normal.x, face.vnt[1].normal.y, face.vnt[1].normal.z);
			const QVector3D normal3(face.vnt[2].normal.x, face.vnt[2].normal.y, face.vnt[2].normal.z);

			const QVector2D texture1(face.vnt[0].texture.x, face.vnt[0].texture.y);
			const QVector2D texture2(face.vnt[1].texture.x, face.vnt[1].texture.y);
			const QVector2D texture3(face.vnt[2].texture.x, face.vnt[2].texture.y);

			const QVector3D o(0, 0.0, 0);

			const VertNormTex vnt1(vertex1*scale+o, normal1, texture1);
			const VertNormTex vnt2(vertex2*scale+o, normal2, texture2);
			const VertNormTex vnt3(vertex3*scale+o, normal3, texture3);

			triangles.addFace(vnt1, vnt2, vnt3);

		}

	}



	void initGL() override {
		build();
		triangles.build();
		loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentTex.glsl");
		program.setUniformValue("texDiffuse", 0);
		program.setUniformValue("texNormalMap", 1);
	}

	/** render the floor */
	void _render(const RenderParams& params) override {
		(void) params;
		triangles.render(&program);
	}



private:

	void build() {
		triangles.build();
	}

};


#endif // OBJECT_H
