/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   new_token_for_each_field.c                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/11/07 02:01:33 by lperrey           #+#    #+#             */
/*   Updated: 2021/11/30 13:46:46 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

t_list	*ft_lstnew_generic(size_t lst_sizse, size_t content_size);

static t_token	*insert_tokens(t_token *t, t_token *insert_lst);

int	new_token_for_each_field(char **fields, t_token **t)
{
	t_token	head;
	t_token	*insert_lst;
	int		i;

	head.next = NULL;
	insert_lst = &head;
	i = 0;
	while (fields[i])
	{
		if (fields[i][0])
		{
			insert_lst->next = (t_token *)ft_lstnew_generic(sizeof(t_token), 0);
			insert_lst = insert_lst->next;
			if (!insert_lst)
			{//todo wrap
				perror("insert_token_for_each_field() error");
				ft_free_2d_arr(fields);
				return ((int)ft_lstclear((t_list **)&head.next, NULL));
			}
			insert_lst->content = fields[i];
			insert_lst->id = T_WORD;
		}
		else
			free(fields[i]);
		i++;
	}
	free(fields);
	*t = insert_tokens(*t, head.next);
	return (1);
}

static t_token	*insert_tokens(t_token *t, t_token *insert_lst)
{
	t_token	*tmp;
	t_token	*insert_lst_last;

	t->id = 0;
	ft_free_null(&t->content);
	if (!insert_lst)
		return (t);

	tmp = t->next;
	t->next = insert_lst;
	insert_lst_last = (t_token *)ft_lstlast((t_list *)insert_lst);
	insert_lst_last->next = tmp;

	return (insert_lst_last);
}
