/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parsing.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/05/16 14:53:00 by cchauvet          #+#    #+#             */
/*   Updated: 2023/05/16 14:54:02 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "./parsing_private.h"
#include "map.h"
#include <stddef.h>
#include <stdlib.h>

static ssize_t	get_nb_line(const char *path)
{
	int		fd;
	char	readed[1];
	size_t	i;

	fd = open(path, O_RDONLY);
	if (fd == -1)
		return (-1);
	i = 1;
	while (read(fd, readed, 1))
	{
		if (readed[0] == '\n')
			i++;
	}
	close(fd);
	return (i);
}

static char	**read_map(const char *path)
{
	int		fd;
	size_t	i;
	char	**map;

	map = malloc(sizeof(char *) * (get_nb_line(path) + 1));
	if (map == NULL)
		return (NULL);
	fd = open(path, O_RDONLY);
	if (fd == -1)
	{
		free(map);
		return (NULL);
	}
	i = 0;
	map[i] = get_next_line(fd);
	while (map[i] != NULL)
	{
		map[i][ft_strlen(map[i]) - 1] = '\0';
		i++;
		map[i] = get_next_line(fd);
	}
	close(fd);
	return (map);
}

void	header_freer(char ***header)
{
	size_t	i;
	size_t	j;

	i = 0;
	while (header[i] != NULL)
	{
		j = 0;
		while (header[i][j] != NULL)
		{
			free(header[i][j]);
			j++;
		}
		free(header[i]);
		i++;
	}
	free(header);
}

int	map_parsing(const char *path, t_map *map)
{
	char	**file_content;
	char	***header;
	size_t	header_size;

	ft_bzero(map, sizeof(t_map));
	if (parsing_meta(path))
		return (1);
	file_content = read_map(path);
	if (file_content == NULL)
	{
		ft_eprintf("map: file error");
		return (1);
	}
	header = get_header((const char **) file_content, &header_size);
	if (header_is_valid(header, map) == 1)
	{
		header_freer(header);
		ft_freer_tab_ultimate(1, file_content);
		return (1);
	}
	header_freer(header);
	map->map = get_body((const char **) file_content, header_size);
	ft_freer_tab_ultimate(1, file_content);
	return (body_is_valid(map) == 0);
}
