#include "renderer.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_blendmode.h>
#include <SDL2/SDL_error.h>
#include <SDL2/SDL_rect.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_scancode.h>
#include <SDL2/SDL_timer.h>
#include <SDL2/SDL_video.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "input.h"
#include "scene.h"

bool running;
MonitorSize_t monitorSize;
SDL_Window* win;
SDL_Renderer * renderer;
const Scene_t * scene;
int scenesCount = 0;
bool fullscreen = false;


static void toggleFullscreen(void) {
	printf("Toggling\n");
	if(!fullscreen) {
		SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN);
		fullscreen = true;
	}
	else {
		SDL_SetWindowFullscreen(win, 0);
		fullscreen = false;
	}
}

//int (*compar)(const void [.size], const void [.size], void *)
void renderer_main(int argc, char ** argv, void(*game_setup)(void), void(*game_loop)(void)) {
	// returns zero on success else non-zero
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
		printf("error initializing SDL: %s\n", SDL_GetError());
	}

	int width = 1280;
	int height = 720;

	if(argc > 2) {
		width = atoi(argv[1]);
		height = atoi(argv[2]);
	}


	win = SDL_CreateWindow("The legend of ADAM", // creates a window
									SDL_WINDOWPOS_CENTERED,
									SDL_WINDOWPOS_CENTERED,
									width, height, 0);

	Uint32 render_flags = SDL_RENDERER_ACCELERATED;

	input_init();
	input_listenKeyDown(SDL_SCANCODE_F11, toggleFullscreen);

	// creates a renderer to render our images
	renderer = SDL_CreateRenderer(win, -1, render_flags);

	if(renderer == NULL) {
		fprintf(stderr, "Could not create renderer\n");
	}

	SDL_GetRendererOutputSize(renderer, &monitorSize.width, &monitorSize.height);


	running = true;

	game_setup();
	while(running) {
		SDL_RenderClear(renderer);

		game_loop();

		SDL_Event event;

		// Events management
		while (SDL_PollEvent(&event)) {
			switch (event.type) {

			case SDL_QUIT:
				// handling of close button
				running = false;
				printf("Quitting my job!\n");
				break;

			case SDL_KEYDOWN:
				// keyboard API for key pressed
				input_pollKeyDown(event.key.keysym.scancode);
				break;
			case SDL_KEYUP:
				input_pollKeyUp(event.key.keysym.scancode);
				break;
			}
		}

		//no need to make an extra render pass
		if(!running) break;

		if(scene != NULL)
			scene_render(scene);

		SDL_RenderPresent(renderer);
		SDL_Delay(1000 / 400); //400fps or u a pussy
	}
}

void renderer_setScene(const Scene_t * newScene) {
	scene = newScene;
}

MonitorSize_t renderer_getMonitorSize() {
	return monitorSize;
}

const Scene_t * renderer_getScene(void){
	return scene;
}
