#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
#include "jshader.h"
#include <SDL3/SDL.h>

#define WIDTH 384
#define HEIGHT 240

int main(int argc, char **argv)
{
	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window *win = SDL_CreateWindow("Shaders i tal", WIDTH*3, HEIGHT*3, SDL_WINDOW_OPENGL);
	if (!win) { printf("ERROR al crear la finestra: %s\n", SDL_GetError()); }

	const int num_drivers = SDL_GetNumRenderDrivers();
	printf("VIDEO DRIVERS AVAILABLE:\n");
	for (int i=0; i<num_drivers;++i) printf("%i: %s\n", i, SDL_GetVideoDriver(i));

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
	SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
	SDL_Renderer *renderer = SDL_CreateRenderer(win, NULL); //-1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
	if (!renderer) { printf("ERROR al crear el renderer: %s\n", SDL_GetError()); }
	SDL_Texture *texTarget = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, WIDTH, HEIGHT);
	if (!win) { printf("ERROR al crear la textura target: %s\n", SDL_GetError()); }

	std::ifstream f("basic.glsl");
	std::string source((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());

	shader::init(win, texTarget, source.c_str());

	// Carreguem una imatge pa ficar algo
	SDL_Texture *bmpTex = SDL_CreateTextureFromSurface(renderer, SDL_LoadBMP("pang.bmp"));
	if (!win) { printf("ERROR al crear la textura sprite: %s\n", SDL_GetError()); }

	bool should_exit = false;

	while (!should_exit)
	{
		SDL_Event e;
		while ( SDL_PollEvent(&e) ) {
			if ( e.type == SDL_EVENT_QUIT || ( e.type == SDL_EVENT_KEY_DOWN && e.key.scancode == SDL_SCANCODE_ESCAPE ) ) { should_exit = true; }
		}

		SDL_SetRenderTarget(renderer, texTarget);
		SDL_RenderTexture(renderer, bmpTex, NULL, NULL);
		
		shader::render();
	}

	SDL_Quit();
	return 0;
}