#ifndef HANDRAIL_H
#define HANDRAIL_H


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


class Handrails : public Renderable {

private:

	Floorplan::Floor* floor;

	GLLines lines;

public:

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


	void initGL() override {
		build();
		lines.build();
		loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentLine.glsl");
		program.setUniformValue("color", QVector4D(0.5, 0.5, 0.5, 1.0));
	}

	/** render the floor */
	void _render(const RenderParams& params) override {
		if (params.clipAboveHeight_m < floor->atHeight) {return;}
		glLineWidth(2);
		lines.render(&program);
	}



private:

	void build() {

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

			if (dynamic_cast<Floorplan::FloorObstacleLine*>(obstacle)) {
				Floorplan::FloorObstacleLine* line = dynamic_cast<Floorplan::FloorObstacleLine*>(obstacle);
				if (line->type != Floorplan::ObstacleType::HANDRAIL) {continue;}
				add(line->from, line->to, floor->getStartingZ());
			}

		}

	}

	void add(const Point2 from, const Point2 to, const float h1) {

		// handrail height
		const float h2 = h1 + 0.8;

		const QVector3D v1(to.x, h2, to.y);
		const QVector3D v2(from.x, h2, from.y);

		// upper
		lines.addLine(v1, v2);

		const float stepSize = 0.5;
		const float len = from.getDistance(to);
		const float steps = std::round(len / stepSize);

		for (int i = 0; i <= steps; ++i) {
			const float percent = (float) i / (float) steps;
			const Point2 pos = from + (to-from) * percent;
			const QVector3D v1(pos.x, h1, pos.y);
			const QVector3D v2(pos.x, h2, pos.y);
			lines.addLine(v1, v2);
		}


	}


};



#endif // HANDRAIL_H
