#include "fdf.h"

int 	wrong_symbols(char **line)
{
	char	*tmp;

	tmp = *line;
	while ((*tmp == '-' || ft_isdigit(*tmp)) && *tmp)
		tmp++;
	if ((ft_strstr(tmp, ",0x") == tmp) && (tmp += 3))
	{
		if (!*tmp)
			return (1);
		else
			while (ft_isdigit(*tmp) || (*tmp >= 'A' && *tmp <= 'F'))
				tmp++;
	}
	if (*tmp)
		return (1);
	return (0);
}

void	wrong_map(void)
{
	ft_putstr("Wrong map!\n");
	quit(0);
}

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

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

int 	map_width(char **tab)
{
	int 	width;
	int 	width_tmp;
	char 	**line_tab;

	line_tab = ft_strsplit(*tab, ' ');
	width =	tab_length(line_tab);
	width_tmp = width;
	while (*tab)
	{
		if ((line_tab = ft_strsplit(*tab, ' ')))
		{
			if (wrong_symbols(line_tab))
				wrong_map();
			if ((width = tab_length(line_tab)) != width_tmp)
				wrong_map();
		}
		free_tab(line_tab);
		tab++;
	}
	return (width);
}


void	min_max_z(t_map *map, int i, int j)
{
	if (map->arr_vec[i][j].z > map->z_max)
		map->z_max = (int)map->arr_vec[i][j].z;
	if (map->arr_vec[i][j].z < map->z_min)
		map->z_min = (int)map->arr_vec[i][j].z;
}

void	to_vec_arr(char **tab, t_map *map)
{
	char 	**line;
	int 	i;
	int 	j;

	map->y_max = tab_length(tab);
	map->x_max = map_width(tab);
	map->arr_vec = malloc(sizeof(t_vec *) * (map->y_max));
	i = 0;
	while (i < map->y_max)
	{
		j = 0;
		line = ft_strsplit(tab[i], ' ');
		map->arr_vec[i] = malloc(sizeof(t_vec) * (map->x_max));
		while (j < map->x_max)
		{
			map->arr_vec[i][j].z = ft_atoi(line[j]);
			map->arr_vec[i][j].x = j;
			map->arr_vec[i][j].y = i;
			min_max_z(map, i, j);
			j++;
		}
		free_tab(line);
		i++;
	}
}

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

	map = malloc(sizeof(t_map));
	map->z_min = 0;
	map->x_max = 0;
	map->x_rot = 0;
	map->y_rot = 0;
	map->z_rot = 0;
	map->scale[0] = 1;
	map->scale[1] = 1;
	map->scale[2] = 1;
	map->low = NULL;
	map->high = NULL;
	if (!(str_map = to_str_map(path)))
	{
		ft_putstr("Wrong path to a map! For help help put \"fdf --help\"\n");
		quit(0);
	}
	tab_map = ft_strsplit(str_map, '\n');
	to_vec_arr(tab_map, map);
	free(str_map);
	free_tab(tab_map);
	return (map);
}