#ifndef OPENGL_WIDGET_HH
#define OPENGL_WIDGET_HH

#include "opengl_mesh.hh"

#include <QOpenGLWidget>
#include <QMatrix4x4>
#include <QOpenGLExtraFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
#include <QTimer>

#define FOV 70


class OpenGLWidget;


class Painter {
public:
	virtual void draw(OpenGLWidget *glw) const = 0;
};


class OpenGLWidget : public QOpenGLWidget, public QOpenGLExtraFunctions {
	Q_OBJECT

	QMatrix4x4 rot, rot_start, proj;
	QMatrix4x4 trans;
	QPoint mouse_pos;
	QTimer move_timer;
	bool move_forward = false;
	bool move_back = false;
	bool move_left = false;
	bool move_right = false;

	QOpenGLShaderProgram main_program;
	QOpenGLShaderProgram skybox_program;
	QOpenGLShaderProgram line_program;
	GLuint skybox_tex;
	GLuint skybox_vao;
	GLuint skybox_vbo;
	OpenGLMesh *ground;

	void loadSkybox();
	void loadGround();
	bool keyEvent(QKeyEvent *e, bool press);

	const Painter *painter = nullptr;

private slots:
	void move();

protected:
    virtual void mousePressEvent(QMouseEvent *e);
    virtual void mouseReleaseEvent(QMouseEvent *e);
    virtual void mouseMoveEvent(QMouseEvent *e);
	virtual void keyPressEvent(QKeyEvent *e);
	virtual void keyReleaseEvent(QKeyEvent *e);
	virtual void focusOutEvent(QFocusEvent *e);

public:
	static OpenGLWidget *instance;

	QVector<OpenGLMesh> meshes;

	OpenGLWidget(QWidget *parent=nullptr);
	~OpenGLWidget();
	void initializeGL() override;
	void resizeGL(int w, int h) override;
	void paintGL() override;
	void setPainter(const Painter *p);
	QOpenGLShaderProgram *getMainProgram();
	QOpenGLShaderProgram *getLineProgram();
	bool project(const QVector3D &p, QPoint &point) const;

signals:
	void initialized();
};


#endif
