#include <libft.h>
#include <cub3d.h>
#include <stdlib.h>

static int
ft_get_tex_no(int fd, t_cub *clist)
{
	char	*line;
	char	**words;

	if (get_next_line(fd, &line) <= 0 || !(words = ft_split(line, ' ')))
	{
		ft_memdel(line);
		return (ft_map_error(2, clist));
	}
	if (!(*words) || ft_strcmp(*words, "NO")
		|| !(*(words + 1)) || (*(words + 2)))
	{
		ft_free_words(words, line);
		return (ft_map_error(2, clist));
	}
	ft_memdel(clist->no_tex_path);
	if (!(clist->no_tex_path = ft_strdup(*(words + 1))))
	{
		ft_free_words(words, line);
		return (-1);
	}
	ft_free_words(words, line);
	return (0);
}

static int
ft_get_tex_so(int fd, t_cub *clist)
{
	char	*line;
	char	**words;

	if (get_next_line(fd, &line) <= 0 || !(words = ft_split(line, ' ')))
	{
		ft_memdel(line);
		return (ft_map_error(3, clist));
	}
	if (!(*words) || ft_strcmp(*words, "SO")
		|| !(*(words + 1)) || (*(words + 2)))
	{
		ft_free_words(words, line);
		return (ft_map_error(3, clist));
	}
	ft_memdel(clist->so_tex_path);
	if (!(clist->so_tex_path = ft_strdup(*(words + 1))))
	{
		ft_free_words(words, line);
		return (-1);
	}
	ft_free_words(words, line);
	return (0);
}

static int
ft_get_tex_we(int fd, t_cub *clist)
{
	char	*line;
	char	**words;

	if (get_next_line(fd, &line) <= 0 || !(words = ft_split(line, ' ')))
	{
		ft_memdel(line);
		return (ft_map_error(4, clist));
	}
	if (!(*words) || ft_strcmp(*words, "WE")
		|| !(*(words + 1)) || (*(words + 2)))
	{
		ft_free_words(words, line);
		return (ft_map_error(4, clist));
	}
	ft_memdel(clist->we_tex_path);
	if (!(clist->we_tex_path = ft_strdup(*(words + 1))))
	{
		ft_free_words(words, line);
		return (-1);
	}
	ft_free_words(words, line);
	return (0);
}

static int
ft_get_tex_ea(int fd, t_cub *clist)
{
	char	*line;
	char	**words;

	if (get_next_line(fd, &line) <= 0 || !(words = ft_split(line, ' ')))
	{
		ft_memdel(line);
		return (ft_map_error(5, clist));
	}
	if (!(*words) || ft_strcmp(*words, "EA")
		|| !(*(words + 1)) || (*(words + 2)))
	{
		ft_free_words(words, line);
		return (ft_map_error(5, clist));
	}
	ft_memdel(clist->ea_tex_path);
	if (!(clist->ea_tex_path = ft_strdup(*(words + 1))))
	{
		ft_free_words(words, line);
		return (-1);
	}
	ft_free_words(words, line);
	return (0);
}

int
ft_get_tex(int fd, t_cub *clist)
{
	if (ft_get_tex_no(fd, clist) < 0 ||
		ft_get_tex_so(fd, clist) < 0 ||
		ft_get_tex_we(fd, clist) < 0 ||
		ft_get_tex_ea(fd, clist) < 0)
		return (-1);
	return (0);
}