/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   get_next_line.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: gtertysh <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2016/12/04 15:59:21 by gtertysh          #+#    #+#             */
/*   Updated: 2016/12/06 19:45:44 by gtertysh         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

static t_fd    *new_node(int fd)
{
    t_fd	*new;

    new = NULL;
    if ((new = (t_fd *)malloc(sizeof(t_fd))))
    {
        new->fd = fd;
        new->n = NULL;
        new->next = NULL;
        new->t = 0;
    }
    return (new);
}

static t_fd    *find_fd(int fd, t_fd **cur_fd)
{
    if (!*cur_fd)
        return ((*cur_fd = new_node(fd)));
    while ((*cur_fd))
    {
        if ((*cur_fd)->fd == fd)
            return (*cur_fd);
        cur_fd = &((*cur_fd)->next);
    }
    return ((*cur_fd = new_node(fd)));
}

int		get_next_line(const int fd, char **line)
{
    static t_fd     *head_fd;
    t_fd            *c;

    if (fd < 0 || !line)
        return (-1);
    *line = ft_strnew(0);
    c = find_fd(fd, &head_fd);
    c->readed = 0;
    if (c->n) {
		if ((c->t = strchr(c->n, '\n')) &&
			(*line = ft_strjoin(*line, ft_strsub(c->n, 0, (c->t - c->n)))) &&
			(c->n = ++(c->t)))
		{
			return (1);
		}
		else if ((*line = ft_strjoin(*line, c->n)))
		{
			c->n = 0;
		}
	}
    while ((c->readed = read(c->fd, c->b, BUFF_SIZE)))
    {
        c->b[c->readed] = 0;
        if ((c->n = strchr(c->b, '\n')) &&
            (*line = ft_strjoin(*line, ft_strsub(c->b, 0, (c->n++ - c->b)))))
            break;
        *line = ft_strjoin(*line, c->b);
    }
    if (!c->readed && !ft_strlen(*line))
        return (0);
    return (1);
}