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

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

	option = my_print_set_option(3, 0x000000ff, 0xffffffff, ASCII_REVERSE);
	my_print_set_position(pos, dialog_pos_x[*dialog_cursor],
	dialog_pos_y[*dialog_cursor]);
	my_print(sfml, pos, dialog[*dialog_cursor], option);
	free(option);
	if ((!(sfml->key & PRES_LSHIFT) && sfml->key & KEY_LSHIFT)
	|| (!(sfml->key & PRES_RSHIFT) && sfml->key & KEY_RSHIFT)
	|| (!(sfml->key & PRES_RIGHT) && sfml->key & KEY_RIGHT)
	|| (!(sfml->key & PRES_ENTER) && sfml->key & KEY_ENTER)
	|| (!(sfml->key & PRES_LEFT) && sfml->key & KEY_LEFT)
	|| (!(sfml->key & PRES_ESC) && sfml->key & KEY_ESC)
	|| (!(sfml->key & PRES_UP) && sfml->key & KEY_UP)
	|| (!(sfml->key & PRES_A) && sfml->key & KEY_A)
	|| (!(sfml->key & PRES_SPACE) && sfml->key & KEY_SPACE)){
		(*dialog_cursor)++;
		sfml->key &= ~(KEY_LSHIFT | KEY_RSHIFT | KEY_RIGHT | KEY_LEFT |
		KEY_UP | KEY_A | KEY_SPACE | KEY_ESC | KEY_ENTER);
	}
}

static void end_main(sfml_t *sfml, int nb_dead)
{
	int fade_active = 0;
	int dialog_cursor = (nb_dead) ? 0 : 5;
	int dialog_end = (nb_dead) ? 5 : 9;

	while (sfRenderWindow_isOpen(sfml->window)
	&& dialog_cursor < dialog_end){
		get_key(sfml);
		game_camera_update(sfml->scene, sfml->width, sfml->height);
		my_clear_vram(sfml, 0xffffffff);
		map_rendering(sfml);
		player_rendering(sfml);
		end_dialog(sfml, &dialog_cursor);
		if (!fade_active)
			fade(sfml, FADE_OPEN);
		else
			my_display_vram(sfml);
		fade_active = 1;
		set_exit(sfml);
	}
}

void end(sfml_t *sfml, int nb_dead)
{
	sfml->scene = new_scene("src/scene_map/map_end.txt", SCENE_LOAD_PLAYER);
	if (sfml == NULL)
		return;
	sfml->key = 0x00;
	end_main(sfml, nb_dead);
	fade(sfml, FADE_CLOSE);
	free_scene(sfml->scene);
	if (nb_dead)
		suicide(sfml, nb_dead);
	else
		text_end(sfml, nb_dead);
}
