#include "input.h"
#include "renderer.h"
#include "text.h"
#include "menu.h"
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_scancode.h>
#include <SDL2/SDL_surface.h>
#include <time.h>
#include <unistd.h>
#include "scaller.h"

long timecode;
long iter;
Mix_Music *prout;

static void space(void) {
	printf("space!\n");
	if(Mix_PlayMusic(prout, -1) != 0){
		printf("Music sound could not be played!\n"
			"SDL_Error: %s\n", Mix_GetError());
		Mix_FreeMusic(prout);
		running = false;
	}
}

static void game_main(void) {
	long delta = time(NULL) - timecode;
	//main game code

	if(iter == 0) {
		menu_render();
		RenderObject_t text;
		SDL_Color white = {255, 255, 255, 255};
		TTF_Init();
		if(text_renderText(&text, 0.1f, 0.1f, 1000, 1, white, "./assets/fonts/arial.ttf", 25, "Hello World") < 0){
			printf("error");
			exit(1);
		}

		SDL_Surface* img = IMG_Load("./assets/img/pp.png");

		RenderObject_t duck = {
			0.5,
			0.5,
			0,
			0.50,
			0.50,
			0,
			img
		};
		scaller(duck.surface, 1, &duck.width, &duck.height);
		placer(duck.surface, 1, &duck.x, &duck.y);

		renderer_renderObject(text);
		renderer_renderObject(duck);

		input_listen(SDL_SCANCODE_SPACE, space);
	}


	//update time
	timecode = time(NULL);
	iter++;
}


int main(void) {
	if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) != 0){
		printf("Music sound could not be open!\n"
			"SDL_Error: %s\n", Mix_GetError());
		running = false;
	}

	prout = Mix_LoadMUS("./assets/music/pet.mp3");
	if(prout == NULL) {
		fprintf(stderr, "Prout not found!\n");
		exit(1);
	}

	iter = 0;
	timecode = time(NULL);

	Mix_Init(MIX_INIT_MP3);
	renderer_main(game_main);

	Mix_FreeMusic(prout);

	Mix_CloseAudio();
	text_freeFontCache();
}
