/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include "game/core.h"
#include "game/draw.h"

static int update_counter(sfml_t *sfml, int *x, int *y, int end_x)
{
	int tmp;

	if (++(*x) == end_x){
		tmp = *x;
		*x = 0;
		(*y)++;
		return (sfml->scene->level->width - tmp);
	}
	return (0);
}

static void check_id(sfml_t *sfml, int x, int y, int i)
{
	uint8_t id;

	if (i >= sfml->scene->level->width * sfml->scene->level->height)
		return;
	id = sfml->scene->level->map[i];
	if (id == ID_GROUND || id == ID_FAKE_GROUND)
		draw_ground(sfml, x, y,
		(i < sfml->scene->level->width) ? ' '
	: sfml->scene->level->map[i - sfml->scene->level->width]);
	if (id == ID_PRINCESS || id == ID_FAKE_PRINCESS)
		draw_princess(sfml, x, y);
	if (id >= ID_PIK_DOWN && id <= ID_PIK_RIGHT)
		draw_pik(sfml, x, y, id - ID_PIK_DOWN);
	if (id >= ID_THROWER_STONE && id <= ID_THROWER_RIGHT)
		draw_thrower(sfml, x, y, id - ID_THROWER_STONE);
}

void map_rendering(sfml_t *sfml)
{
	int offset_x = sfml->scene->camera->x & 0x3f;
	int offset_y = sfml->scene->camera->y & 0x3f;
	int load_x = (!offset_x) ? BLOCK_LOAD_X : BLOCK_LOAD_X + 1;
	int load_y = (!offset_y) ? BLOCK_LOAD_Y : BLOCK_LOAD_Y + 1;
	int end_y = ((sfml->scene->camera->y >> 6) + load_y)
	* sfml->scene->level->width;
	int end_x = (sfml->scene->camera->x >> 6) + load_x;
	int i = (sfml->scene->camera->x >> 6) +
	(sfml->scene->camera->y >> 6) * sfml->scene->level->width - 1;
	int x = -1;
	int y = 0;

	end_y = (end_y > sfml->scene->level->height *
	sfml->scene->level->width)
	? sfml->scene->level->height * sfml->scene->level->width : end_y;
	end_x = (end_x > sfml->scene->level->width) ?
sfml->scene->level->width : end_x;
	while (++i < end_y){
		i += update_counter(sfml, &x, &y, end_x);
		check_id(sfml, (x << 6) - offset_x, (y << 6) - offset_y, i);
	}
}
