#include "fdf.h"

void	fill_row(t_list **list, int i, char *row)
{
	int		j;
	char 	**row_numbers;
	t_vec	vec3;

	j = 0;
	vec3.y = i;
	row_numbers = ft_strsplit(row, ' ');
	while (row_numbers[j])
	{
		vec3.x = j;
		vec3.z = ft_atoi(row_numbers[j]);
		ft_lstadd_back(list, &vec3, sizeof(t_vec));
		j++;
	}
	free_tab(row_numbers);
}

t_list	*to_lst_map(char **tab_map)
{
	int 	i;
	t_list	*lst_map;

	lst_map = NULL;
	i = 0;
	while (tab_map[i])
	{
		fill_row(&lst_map, i, tab_map[i]);
		i++;
	}
	return (lst_map);
}

char	*to_str_map(char *path)
{
	int 	fd;

	fd = open(path, O_RDONLY);
	if (fd != -1)
		return (ft_read_file(fd));
	return (0);
}

void	map_dimensions(t_map *map)
{
	int 	x;
	int 	y;
	int 	z;
	t_list	*l;

	l = map->lst_map;
	x = 0;
	y = 0;
	z = 0;
	while (l)
	{
		if (((t_vec *)(l->content))->x > x)
			x = (int)((t_vec *)(l->content))->x;
		if (((t_vec *)(l->content))->y > y)
			y = (int)((t_vec *)(l->content))->y;
		if (((t_vec *)(l->content))->z > z)
			z = (int)((t_vec *)(l->content))->z;
		l = l->next;
	}
	map->x_max = x;
	map->y_max = y;
	map->z_max = z;
}

t_map	*map_init(char *path)
{
	char 	*str_map;
	char 	**tab_map;
	t_map	*map;

	map = malloc(sizeof(t_map));
	if (!(str_map = to_str_map(path)))
	{
		quit(0);
	}
	tab_map = ft_strsplit(str_map, '\n');
	map->lst_map = to_lst_map(tab_map);
	map_dimensions(map);
	free(str_map);
	free_tab(tab_map);
	return (map);
}