/*
 * Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#pragma once

#include <nostalgia/core/gfx.hpp>
#include <nostalgia/geo/point.hpp>
#include <nostalgia/geo/vec.hpp>
#include <nostalgia/glutils/glutils.hpp>
#include <nostalgia/studio/studio.hpp>

namespace nostalgia::core {

class TileSheetGrid {

	private:
		static constexpr auto VertexVboRows = 1;
		static constexpr auto VertexVboRowLength = 7;
		static constexpr auto VertexVboLength = VertexVboRows * VertexVboRowLength;

		static constexpr auto VShad = R"glsl(
		{}
		in vec2 vPt1;
		in vec2 vPt2;
		in vec3 vColor;
		out vec2 gPt2;
		out vec3 gColor;
		void main() {
			gColor = vColor;
			gl_Position = vec4(vPt1, 0.0, 1.0);
			gPt2 = vPt2;
		})glsl";

		static constexpr auto FShad = R"glsl(
		{}
		in vec3 fColor;
		out vec4 outColor;
		void main() {
			outColor = vec4(fColor, 1);
			//outColor = vec4(0.4431, 0.4901, 0.4941, 1.0);
		})glsl";

		static constexpr auto GShad = R"glsl(
		{}
		layout(points) in;
		layout(line_strip, max_vertices = 2) out;
		in vec3 gColor[];
		in vec2 gPt2[];
		out vec3 fColor;
		uniform vec2 gScroll;
		void main() {
			fColor = gColor[0];
			gl_Position = gl_in[0].gl_Position + vec4(gScroll, 0, 0);
			EmitVertex();
			gl_Position = vec4(gPt2[0] + gScroll, 0, 1);
			EmitVertex();
			EndPrimitive();
		})glsl";

		glutils::GLProgram m_shader;
		glutils::BufferSet m_bufferSet;
		float m_pixelSizeMod = 1;

	public:
		void setPixelSizeMod(float sm) noexcept;

		ox::Error buildShader() noexcept;

		void draw(bool update, const geo::Vec2 &scroll) noexcept;

		void initBufferSet(const geo::Vec2 &paneSize, const TileSheet::SubSheet &subsheet) noexcept;

	private:
		static void setBufferObject(geo::Point pt1, geo::Point pt2, Color32 c, float *vbo, const geo::Vec2 &pixSize) noexcept;

		void setBufferObjects(const geo::Vec2 &paneSize, const TileSheet::SubSheet &subsheet) noexcept;

		[[nodiscard]]
		geo::Vec2 pixelSize(const geo::Vec2 &paneSize) const noexcept;

};

}
