#include "pch.h"
#include "LUT.h"

#include "Engine.h"
#include "gl/Texture.h"
// #include <iostream>
#include <filesystem>

void LUT::load_lut(std::string_view path) {
	std::string pp = std::string("src/assets/luts/") + &path[0];
		
	// Load .CUBE file
	FILE * file = fopen(&pp[0], "r");
	if (file == NULL){
		wlog_err("Couldn't open LUT");
	}

	int size = 0;

	int row = 0;
	while (true){
		char line[128];
		if (fgets(line, sizeof(line), file) == NULL) {
			break;
		}
		// fscanf(file, "%128[^\n]\n", line);

		// if (strcmp(line, "LUT_3D_SIZE") == 0){
		if(size != 0) {
			// Read colors
			float r, g, b;
			int s = sscanf(line, "%f %f %f", &r, &g, &b);
			if(s == 3) {
				this->data[row * 4 + 0] = r;
				this->data[row * 4 + 1] = g;
				this->data[row * 4 + 2] = b;
				this->data[row * 4 + 3] = 1;
				row++;
			}
			// fscanf(file, "%128[^\n]\n", line);
			if (row >= size * size * size) {
				break;
			}
		} else if (strstr(line, "LUT_3D_SIZE") == line){
			// Read LUT size
			// fscanf(file, "%s %i\n", line, &size);
			if (sscanf(line, "LUT_3D_SIZE %i", &size) != 1) {
				printf("Error: Invalid LUT size\n");
				// return false;
			}
				
			this->data.resize(size * size * size * 4);
		}
	}
		
	fclose(file);

	if(this->tex) {
		this->tex->destroy();
		WEngine->alloc_textures.pop(*this->tex);
	}
		
	{
		// Texture
		TextureDesc tex_desc = TextureDesc{
			.resx = (uint32_t)size, .resy = (uint32_t)size, .resz = (uint32_t)size,
			.internal_format = InternalFormat::RGBA32F, .tex_access = TexAccess::READ
		};
		this->tex = WEngine->alloc_textures.push(tex_desc).ptr;
		this->tex->upload_data(&this->data[0]);
	}
}

LUT::LUT(std::string_view path) {
	lut_paths.reserve(100);
	const std::string folder_path = "./src/assets/luts";

	// Check if the folder exists
	// if (!fs::exists(folder_path) || !fs::is_directory(folder_path)) {
	// 	std::cerr << "Error: Folder does not exist or is not a directory\n";
	// 	return 1;
	// }

	// Iterate through files in the folder
	for (const auto& entry : std::filesystem::directory_iterator(folder_path)) {
		if (entry.is_regular_file() && entry.path().extension() == ".cube") {
			std::string path_str = entry.path().filename().string();
			// entry.path().filename().c_str()
			lut_paths.push_back(path_str.c_str());
			// std::cout << entry.path().filename() << '\n';
		}
	}

	load_lut(path);
}
