/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include "lib/my_graphics.h"
#include "game/kinematic.h"
#include "game/message.h"
#include "game/ascii.h"
#include "game/game.h"
#include "game/core.h"
#include "game/draw.h"
#include "game/menu.h"
#include "game/memory.h"
#include <stdlib.h>

static void show_hud(sfml_t *sfml, int nb_dead)
{
	uint32_t *option;
	int pos[2];

	option = my_print_set_option(3, 0x000000ff, 0xffffffff, ASCII_REVERSE);
	pos[0] = 8;
	pos[1] = 8;
	my_print(sfml, pos, "Dead:", option);
	pos[0] = 168;
	pos[1] = 8;
	if (!nb_dead)
		my_print(sfml, pos, "0", option);
	else
		my_print_nbr(sfml, nb_dead, option, pos);
	free(option);
}

static void rendering(sfml_t *sfml, int *fade_active)
{
	my_clear_vram(sfml, 0xffffffff);
	map_rendering(sfml);
	player_rendering(sfml);
	wall_rendering(sfml);
	draw_thrower_object(sfml);
	collision_show(sfml);
	check_message(sfml, sfml->scene->message);
	show_hud(sfml, sfml->scene->player->nb_dead);
	if (!*fade_active){
		fade(sfml, FADE_OPEN);
		*fade_active = 1;
	}
	else
		my_display_vram(sfml);
}

static void game_update_object(sfml_t *sfml)
{
	get_key(sfml);
	if (!(sfml->scene->player->action & PLAYER_DEAD))
		update_player(sfml);
	#ifndef NO_WALL_MOVE
	update_wall(sfml);
	#endif
	update_thrower(sfml, sfml->scene->thrower, sfml->scene->level);
}

void game_main(sfml_t *sfml, char *map_name)
{
	int fade_active;
	int exit = 1;

	fade_active = 0;
	sfml->scene = new_scene(map_name, SCENE_LOAD_ALL_GAME);
	if (sfml->scene == NULL)
		return;
	while (sfRenderWindow_isOpen(sfml->window)
	&& !(sfml->scene->player->action & PLAYER_WIN) && exit){
		game_camera_update(sfml->scene, sfml->width, sfml->height);
		rendering(sfml, &fade_active);
		game_update_object(sfml);
		exit = check_pause(sfml);
		set_exit(sfml);
	}
	free_scene(sfml->scene);
	fade(sfml, FADE_CLOSE);
	if (exit)
		end(sfml, sfml->scene->player->nb_dead);
}
