#include <stdio.h>
#include <stdlib.h>
#include "sdl.h"
#include "parser.h"

void CleanUp_SDL(APP *app) {
	if (app->window)
		SDL_DestroyWindow(app->window);

	if (app->render)
		SDL_DestroyRenderer(app->render);

	SDL_Quit();
	IMG_Quit();
	TTF_Quit();
}

int Init_SDL(const CONFIG cfg, APP *app) {
	memset(app, 0, sizeof(APP));

	int status = 0;
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
		goto Init_SDL_CLOSE;

	/* Get display mode if fullscreen enabled in config */
	app->scr_width = cfg.screen_w;
	app->scr_height = cfg.screen_h;
	int fullscreen = 0;

	if (cfg.fullscreen) {
		if (!cfg.fullscreen_custom) {
			SDL_DisplayMode dm;
			if (SDL_GetDesktopDisplayMode(0, &dm) < 0)
				goto Init_SDL_CLOSE;

			app->scr_width = dm.w;
			app->scr_height = dm.h;
		}

		fullscreen = SDL_WINDOW_FULLSCREEN;
	}

	/* Creating window */
	app->window = SDL_CreateWindow("LPT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, app->scr_width, app->scr_height, SDL_WINDOW_RESIZABLE | fullscreen);
	if (!app->window)
		goto Init_SDL_CLOSE;
	SDL_SetWindowMinimumSize(app->window, 640, 480);

	/* Renderer */
	app->render = SDL_CreateRenderer(app->window, -1, SDL_RENDERER_ACCELERATED | (cfg.vsync) ? SDL_RENDERER_PRESENTVSYNC : 0);
	if (!app->render)
		goto Init_SDL_CLOSE; 

	/* Image subsystem */
	status = 1;
	int flags = IMG_INIT_PNG;
	if (!(IMG_Init(flags) & flags))
		goto Init_SDL_CLOSE;

	/* Font subsystem */
	status = 2;
	if (TTF_Init() < 0)
		goto Init_SDL_CLOSE;

	return 0;


Init_SDL_CLOSE:
	if (status == 1)
		fprintf(stderr, "Could not initialize SDL_IMG: %s\n", IMG_GetError());

	if (status == 2)
		fprintf(stderr, "Could not initialize SDL_TTF: %s\n", TTF_GetError());

	else
		fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());

	CleanUp_SDL(app);
	return 1;
}

SDL_Texture *LoadIMG_SDL(const char *path, APP *app) {
	if (path == NULL) {
		fputs("LoadIMG: path is NULL. Maybe incorrect scene syntax\n", stderr);
		return NULL;
	}

	SDL_Texture *text = IMG_LoadTexture(app->render, path);
	if (text == NULL) {
		fprintf(stderr,  "LoadIMG: %s\n", SDL_GetError());
		return NULL;
	}

	return text;
}
