#ifndef DOORS_H
#define DOORS_H

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

class Doors : public Renderable {

private:

	Floorplan::Floor* floor;

	GLTriangles<VertNormTexTan> doors;

public:

	/** ctor */
	Doors(Floorplan::Floor* floor) : floor(floor) {
		;
	}


	void initGL() override {

		build();
		doors.setDiffuse(":/res/gl/tex/door2.jpg");
		doors.setNormalMap(":/res/gl/tex/door2_normal.jpg");

		doors.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 {

		// skip me?
		if (params.clipAboveHeight_m < floor->atHeight) {return;}

		doors.render(&program);

	}



private:

	void build() {

		for (Floorplan::FloorObstacle* obstacle : floor->obstacles) {

			if (dynamic_cast<Floorplan::FloorObstacleDoor*>(obstacle)) {
				Floorplan::FloorObstacleDoor* door = dynamic_cast<Floorplan::FloorObstacleDoor*>(obstacle);
				addFace(door->from, door->to, floor->getStartingZ(), floor->getStartingZ() + door->height, door->swap);
			}

		}

	}

	void addFace(const Point2 from, Point2 to, const float h1, const float h2, const bool swap) {

		to = from + (to-from).rotated(60/180.0f*M_PI * ((swap)?(-1):(+1)) );

		const QVector3D vert1(from.x, h1, from.y);
		const QVector3D vert2(to.x, h1, to.y);
		const QVector3D vert3(to.x, h2, to.y);
		const QVector3D vert4(from.x, h2, from.y);

		const QVector3D n1 = GLHelper::getNormal(vert1, vert2, vert3);
		const QVector3D n2 = -n1;

		QVector3D tan = (vert1-vert2).normalized();
		tan = GLHelper::isCCW(vert1, vert2, vert3) ? (tan) : (-tan);

		const QVector2D tex1(0, 0);
		const QVector2D tex2(1, 0);
		const QVector2D tex3(1, 1);
		const QVector2D tex4(0, 1);

		{
			const VertNormTexTan vnt1(vert1, n1, tex1, tan);
			const VertNormTexTan vnt2(vert2, n1, tex2, tan);
			const VertNormTexTan vnt3(vert3, n1, tex3, tan);
			const VertNormTexTan vnt4(vert4, n1, tex4, tan);
			doors.addQuadCCW(vnt1, vnt2, vnt3, vnt4);
		} {
			const VertNormTexTan vnt1(vert1, n2, tex1, -tan);
			const VertNormTexTan vnt2(vert2, n2, tex2, -tan);
			const VertNormTexTan vnt3(vert3, n2, tex3, -tan);
			const VertNormTexTan vnt4(vert4, n2, tex4, -tan);
			doors.addQuadCW(vnt1, vnt2, vnt3, vnt4);
		}

	}



};

#endif // DOORS_H
