#include <GL4D/gl4duw_SDL2.h>
#include <GL4D/gl4du.h>
#include <GL4D/gl4dg.h>
#include <GL4D/gl4dp.h>
#include <SDL_image.h>
#include "animations.h"
#include "audioHelper.h"

static int _ww = 1920;
static int _wh = 1080;
static GLuint _quadId = 0;
static GLuint _pId = 0;
static GLuint _texId = 0;

static void init(void);
static void draw(void);
static void quit(void);

/*
int main(int argc, char** argv){
	if(!gl4duwCreateWindow(argc, argv, "GL4Dummies", 20, 20, _ww, _wh, GL4DW_RESIZABLE | GL4DW_SHOWN))
		return 1;
	init();
	atexit(quit);
	gl4duwDisplayFunc(draw);
	gl4duwMainLoop();
	return 0;
}
*/

void sceneCred(int state){
	switch(state){
	case GL4DH_INIT:
		init();
		return;
	case GL4DH_FREE:
		quit();
		return;
	case GL4DH_UPDATE_WITH_AUDIO:
		return;
	default:
		draw();
		return;
	}
}

static void init(void){
	_pId = gl4duCreateProgram("<vs>shaders/credits.vs","<fs>shaders/credits.fs",NULL);
	_quadId = gl4dgGenQuadf();

	glClearColor(0.0,0.0,0.0,1);
	
	gl4duGenMatrix(GL_FLOAT, "proj");
	gl4duGenMatrix(GL_FLOAT, "mod");
	gl4duGenMatrix(GL_FLOAT, "view");
	
	glGenTextures(1, &_texId);
	glBindTexture(GL_TEXTURE_2D, _texId);

	SDL_Surface *s = IMG_Load("images/credits.png");
	assert(s);
	SDL_Surface* d = SDL_CreateRGBSurface(0, s->w, s->h, 32, R_MASK, G_MASK, B_MASK, A_MASK);
	SDL_BlitSurface(s,NULL,d,NULL);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, d->w, d->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, d->pixels);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	SDL_FreeSurface(s);
	SDL_FreeSurface(d);
	gl4duBindMatrix("proj");
	gl4duLoadIdentityf();
	gl4duFrustumf(-1.0f, 1.0f, -1.0f * _wh/_ww, 1.0f * _wh/_ww, 2.0f, 1000.0f);
}


static void draw(void){
	static double elapsed = 0.0, pt = -1.0;
	double tmpt, dt;
	if(pt<0.0)
		pt = gl4dGetElapsedTime();
	dt = ((tmpt = gl4dGetElapsedTime()) - pt) / 1000.0;
	pt = tmpt;
	elapsed += dt;
	// Fin bloc temps

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glUseProgram(_pId);
	
	gl4duBindMatrix("view");
	gl4duLoadIdentityf();
	gl4duLookAtf(0,0,0,
				 0,0,-1,
				 0,1,0);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);

	gl4duBindMatrix("mod");
	gl4duLoadIdentityf();
	gl4duTranslatef(0,0,-4.5);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, _texId);
	glUniform1i(glGetUniformLocation(_pId, "tex"), 0);
	glUniform1i(glGetUniformLocation(_pId, "inv"), 1);
	glUniform1f(glGetUniformLocation(_pId, "transp"), 1.0);
	glUniform1f(glGetUniformLocation(_pId, "tresh"), elapsed/5.0);
	glUniform1f(glGetUniformLocation(_pId, "pixMult"), 100.0);
	gl4duSendMatrices();
	gl4dgDraw(_quadId);
	
}

static void quit(void){
	if(_texId)
		glDeleteTextures(1, &_texId);
}
