#include "../external/glad/src/gl.c"

#include "assets.cpp"

// ::Globals::

PipelineCreateInfo g_Pipeline_Create_Info[] = {
	{ .vertex_shader = "shaders/pbr.vert", .fragment_shader = "shaders/pbr.frag" },
	//{ .vertex_shader = "shaders/gui.vert", .fragment_shader = "shaders/gui.frag" },
};

// ::Init::Impl::Start::

rIndexedBuffer yoder;

static b32
Init(Renderer *renderer)
{
	b32 success = true;

	RGFW_setGLHint(RGFW_glMajor, 4);
	RGFW_setGLHint(RGFW_glMinor, 6);
	RGFW_setGLHint(RGFW_glProfile, RGFW_glCore);

	renderer->window = RGFW_createWindow("Video Game", RGFW_RECT(0, 0, 1280, 720), RGFW_windowCenter | RGFW_windowNoResize);
	if (renderer->window == NULL)
	{
		Printfln("Failed to create window");
		success = false;
	}

	if (success)
	{
		RGFW_window_makeCurrent(renderer->window);

		int glad_version = gladLoaderLoadGL();
		if (!glad_version)
		{
			Printfln("gladLoaderLoadGL failure");
			success = false;
		}
	}

	for (u32 i = 0; i < PIPELINE_MAX; i += 1)
	{
		renderer->pipelines[i] = BuildPipeline(g_Pipeline_Create_Info + i);
	}

	yoder = rLoadModel("models/yoda");

	return success;
}

static b32 
InitModels(Renderer *renderer)
{
	b32 success = true;

	for (u64 i = 0; i < MODEL_ASSET_MAX; i += 1)
	{
		u64 hash = g_Model_Asset_Hashes[i];
		Asset asset = apLoadWithHash(hash);
		Assert(asset.model != NULL, "InitModels failure: Model loaded is NULL");

	}

	return success;
}

static PipelineHandle 
BuildPipeline(PipelineCreateInfo *create_info)
{
	auto vertex_shader = CreateShader(GL_VERTEX_SHADER);
	Assert(BuildShader(&vertex_shader, create_info->vertex_shader), "BuildShader vertex failure");

	auto fragment_shader = CreateShader(GL_FRAGMENT_SHADER);
	Assert(BuildShader(&fragment_shader, create_info->fragment_shader), "BuildShader fragment failure");

	auto pipeline = CreatePipeline();
	glAttachShader(pipeline, vertex_shader);
	glAttachShader(pipeline, fragment_shader);
	glLinkProgram(pipeline);

	int success = 0;
	glGetProgramiv(pipeline, GL_LINK_STATUS, &success);
	if (!success)
	{
		char info_log[512];
		glGetProgramInfoLog(pipeline, 512, NULL, info_log);
		Assert(false, "Failed to build pipeline");
	}

	return pipeline;
}

static b32 
BuildShader(ShaderHandle *handle, char *asset)
{
	b32 success = true;

	Asset data = apLoad(asset);
	Assert(data.bytes != NULL && asset, "Shader data is NULL");

	glShaderBinary(1, handle, GL_SHADER_BINARY_FORMAT_SPIR_V, data.bytes, data.len);
	glSpecializeShader(*handle, "main", 0, 0, 0);

	int compiled = 0;
	glGetShaderiv(*handle, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		char info_log[512];
		glGetShaderInfoLog(*handle, 512, NULL, info_log);
		Printfln("Unable to compile shader: %s", info_log);
		success = false;
	}

	return success;
}

static PipelineHandle 
CreatePipeline()
{
	PipelineHandle pipeline = glCreateProgram();
	return pipeline;
}

static VertexBuffer 
CreateVertexBuffer()
{
	VertexBuffer buf;
	glGenBuffers(1, &buf);

	return buf;
}

static IndexBuffer 
CreateIndexBuffer()
{
	IndexBuffer buf;
	glGenBuffers(1, &buf);

	return buf;
}

static VertexArray
CreateVertexArray()
{
	VertexArray array;
	glGenVertexArrays(1, &array);

	return array;
}

static ShaderHandle 
CreateShader(int type)
{
	return (ShaderHandle)glCreateShader(type);
}

static rIndexedBuffer
rLoadModel(char *asset)
{
	rIndexedBuffer mesh = {0};

	/*
	mesh.array = CreateVertexArray();
	mesh.vertex = CreateVertexBuffer();
	mesh.index = CreateIndexBuffer();

	glBindVertexArray(mesh.array);
	glBindBuffer(GL_ARRAY_BUFFER, mesh.vertex);

	Asset data = apLoad(asset);
	Assert(data.model != NULL, "CreateMeshBuffer failed to load asset");

	mesh.draw_count = data.model_meta.i_count;

	Printfln("v_count: %llu", data.model->v_count);

	glBufferData(
		GL_ARRAY_BUFFER, 
		data.model->v_count * sizeof(apVertex),
		data.model->vertices,
		GL_STATIC_DRAW
	);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.index);
	glBufferData(
		GL_ELEMENT_ARRAY_BUFFER,
		data.model->i_count * sizeof(u32),
		data.model->indices,
		GL_STATIC_DRAW
	);

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(apVertex), 0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(apVertex), (void *)offsetof(apVertex, col));

	apUnload(asset);

	glBindVertexArray(0);

	*/

	return mesh;
}


// ::Init::Impl::End::


// ::Draw::Impl::Start::

static void
DrawIndexedBuffer(rIndexedBuffer *buffer)
{
	glBindVertexArray(buffer->vao);
	glDrawElements(GL_TRIANGLES, buffer->icount, GL_UNSIGNED_INT, (void *)buffer->ioffset);
}


// ::Draw::Impl::End::


// ::Buffers::Impl::Start::

static rIndexedBuffer
CreateIndexedBuffer(rawptr vert_data, u32 vcount, rawptr idx_data, u32 icount)
{
	i32 alignment = GL_NONE;
	glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &alignment);

	u32 vao = GL_NONE;
	u32 buffer = GL_NONE;

	isize vert_len = isize(vcount * sizeof(apVertex));
	isize idx_len = isize(icount * sizeof(u32));

	isize vert_len_aligned = Align(vert_len, alignment);
	isize idx_len_aligned = Align(idx_len, alignment);

#if BUILD_DEBUG
	Assert((vert_len_aligned / alignment) == 0, "Buffers are not aligned");
	Assert((idx_len_aligned / alignment) == 0, "Buffers are not aligned");
#endif

	isize vert_offset = 0;
	isize idx_offset = vert_len_aligned;

	glCreateBuffers(1, &buffer);
	glNamedBufferStorage(buffer, idx_len_aligned + vert_len_aligned, NULL, GL_DYNAMIC_STORAGE_BIT);

	glNamedBufferSubData(buffer, vert_offset, vert_len, vert_data);
	glNamedBufferSubData(buffer, idx_offset, idx_len, idx_data);

	glCreateVertexArrays(1, &vao);

	constexpr u32 pos_size = SizeOfMember(apVertex, pos) / sizeof(f32);
	glEnableVertexArrayAttrib(vao, 0);
	glVertexArrayAttribBinding(vao, 0, 0);
	glVertexArrayAttribFormat(vao, 0, pos_size, GL_FLOAT, GL_FALSE, 0);

	constexpr u32 normal_size = SizeOfMember(apVertex, normal) / sizeof(f32);
	glEnableVertexArrayAttrib(vao, 1);
	glVertexArrayAttribBinding(vao, 1, 0);
	glVertexArrayAttribFormat(vao, 1, normal_size, GL_FLOAT, GL_FALSE, offsetof(apVertex, normal));

	constexpr u32 uv_size = SizeOfMember(apVertex, uv) / sizeof(f32);
	glEnableVertexArrayAttrib(vao, 2);
	glVertexArrayAttribBinding(vao, 2, 0);
	glVertexArrayAttribFormat(vao, 2, uv_size, GL_FLOAT, GL_FALSE, offsetof(apVertex, uv));

	glVertexArrayVertexBuffer(vao, 0, buffer, vert_offset, sizeof(apVertex));
	glVertexArrayElementBuffer(vao, buffer);

	rIndexedBuffer indexed_buffer = {0};
	indexed_buffer.ioffset = idx_offset;
	indexed_buffer.icount = icount;
	indexed_buffer.vao = vao;
	indexed_buffer.buffer = buffer;

	return indexed_buffer;
}

// ::Buffers::Impl::End::



// ::Textures::Impl::Start::

static u32 
CreateTexture(rawptr data, u32 width, u32 height, u32 channels)
{
	u32 tex;
	glCreateTextures(GL_TEXTURE_2D, 1, &tex);

	i32 mipmap = Mini32(5, i32(log2f(f32(Maxi32(width, height)))));

	u32 format, copy_format;
	switch (channels) 
	{
	case 1:
		format = GL_R8;
		copy_format = GL_RED;
		break;
	case 2:
		format = GL_RG8;
		copy_format = GL_RG;
	case 3:
		format = GL_RGB8;
		copy_format = GL_RGB;
	case 4:
		format = GL_RGBA8;
		copy_format = GL_RGBA;
	default:
		Assert(false, "CreateTexture failure: unsupported channel number passed in");
	}

	glTextureStorage2D(tex, mipmap, format, width, height);
	glTextureSubImage2D(tex, 0, 0, 0, width, height, copy_format, GL_UNSIGNED_BYTE, data);

	glTextureParameteri(tex, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTextureParameteri(tex, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTextureParameterf(tex, GL_TEXTURE_BASE_LEVEL, 0);
	glTextureParameteri(tex, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTextureParameteri(tex, GL_TEXTURE_WRAP_T, GL_REPEAT);

	glGenerateTextureMipmap(tex);

	return tex;
}

// ::Textures::Impl::End::

static b32
RunCycle(Renderer *renderer)
{
	while (RGFW_window_checkEvent(renderer->window));

	Asset yoder = apLoad("models/yoda");

	glUseProgram(renderer->pipelines[PIPELINE_PBR]);

	glClearColor(0.1f, 0.8f, 0.4f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	//DrawMeshBuffer(&yoder);

	RGFW_window_swapBuffers(renderer->window);

	return !RGFW_window_shouldClose(renderer->window);
}
