/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include "game/memory.h"
#include "game/core.h"
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

static void fill_line(level_t *level, int x, int y)
{
	while (x < level->width)
		level->map[x+++ y * level->width] = (uint8_t)' ';
}

static void map_cpy(level_t *level, uint8_t *tmp, int size)
{
	int i = 0;
	int j = 0;
	int x = 0;
	int y = 0;

	while (level->file_height +++i < MAP_HEIGHT_MIN)
		fill_line(level, x, y++);
	i = -1;
	while (++i < size){
		if (tmp[i] == '\n'){
			fill_line(level, x, y);
			x = 0;
			y++;
		}
		else
			level->map[x+++ y * level->width] = (uint8_t)tmp[i];
	}
}

static void get_info_map(level_t *level, uint8_t *tmp, int size)
{
	int i = -1;
	int x = 0;
	int y = 0;

	level->width = 0;
	level->height = 0;
	while (++i < size){
		x++;
		x = (tmp[i] == '\n') ? 0 : x;
		level->height += (tmp[i] == '\n') ? 1 : 0;
		level->width = (level->width > x) ? level->width : x;
	}
	level->file_width = level->width;
	level->file_height = level->height;
	if (level->width < MAP_WIDTH_MIN)
		level->width = MAP_WIDTH_MIN;
	if (level->height < MAP_HEIGHT_MIN)
		level->height = MAP_HEIGHT_MIN;
}

/* Ugly but my getnextline is not stable so   */
/* I use a huge buffer to read all the file   */
/* and malloc "properly".                     */
level_t *load_map(const char *file)
{
	uint8_t tmp[1000000];
	level_t *level;
	int handle = open(file, O_RDONLY);
	int size;

	if (handle < 0){
		write(2, "Error when open map file.\n", 26);
		return (NULL);
	}
	size = read(handle, tmp, 1000000);
	if (!size || read(handle, tmp, 1000000)){
		write(2, "Error when read map file.\n", 26);
		close(handle);
		return (NULL);
	}
	level = (level_t*)malloc(sizeof(level_t));
	get_info_map(level, tmp, size);
	level->map = (uint8_t*)malloc((level->width * level->height) << 2);
	map_cpy(level, tmp, size);
	close(handle);
	return (level);
}
