/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   get_next_line.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: erey-bet <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/10/15 23:42:35 by erey-bet          #+#    #+#             */
/*   Updated: 2022/12/12 17:19:23 by erey-bet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "get_next_line.h"

static char	*read_line(int fd)
{
	char	*buff;
	int		y;

	buff = ft_calloc_gnl(BUFFER_SIZE + 1, 1);
	if (buff == NULL)
		return (NULL);
	y = read(fd, buff, BUFFER_SIZE);
	if (y == -1)
	{
		free(buff);
		return (NULL);
	}
	buff[y] = '\0';
	return (buff);
}

static char	*join_str(char *s1, char *s2)
{
	char	*n_str;
	int		i;
	int		len;

	len = ft_strlen_gnl(s1);
	n_str = ft_calloc_gnl(len + ft_strlen_gnl(s2) + 1, 1);
	if (n_str == NULL)
		return (NULL);
	i = -1;
	if (s1 != NULL)
		while (s1[++i])
			n_str[i] = s1[i];
	i = -1;
	while (s2[++i])
		n_str[i + len] = s2[i];
	n_str[i + len] = '\0';
	free(s1);
	free(s2);
	return (n_str);
}

static char	*get_text(char *save)
{
	int		i;
	char	*new_s;

	i = 0;
	while (save[i] && save[i] != '\n')
		i++;
	if (save[i] == '\n')
		i++;
	new_s = ft_calloc_gnl(i + 1, 1);
	if (new_s == NULL)
		return (NULL);
	ft_strlcpy_gnl(new_s, save, i + 1);
	ft_strlcpy_gnl(save, save + i, ft_strlen_gnl(save));
	return (new_s);
}

static void	*make_free(char *buff, char **save, int choice)
{
	if (choice == 1)
	{
		free(buff);
		free(*save);
	}
	else
	{
		free(*save);
		*save = NULL;
	}
	return (NULL);
}

char	*get_next_line(int fd)
{
	char		*buff;
	char		*str;
	static char	*save;

	buff = NULL;
	while (buff == NULL || (ft_strchr_gnl(save, '\n') == -1))
	{
		buff = read_line(fd);
		if (buff == NULL
			|| (ft_strlen_gnl(buff) == 0 && ft_strlen_gnl(save) == 0))
			return (make_free(buff, &save, 1));
		if (ft_strlen_gnl(buff) == 0)
		{
			free(buff);
			break ;
		}
		save = join_str(save, buff);
		if (save == NULL)
			return (NULL);
	}
	str = get_text(save);
	if (ft_strlen_gnl(save) == 0)
		make_free(NULL, &save, 2);
	return (str);
}
