/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parser_get_commands.c                              :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/02/11 14:06:02 by qmennen           #+#    #+#             */
/*   Updated: 2025/02/18 20:36:01 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"
#include "utils.h"

static int		is_command_token(t_token *token)
{
	return (token->type < 3 || redirect_token_type(token));
}

static int		validate_redirects(t_list *lst)
{
	t_list	*token;

	token = lst;
	while (token)
	{
		if (((t_redirect *)token->content)->type == T_ERROR)
			return (0);
		token = token->next;
	}
	return (1);
}

t_list	*parser_get_commands(t_minishell *msh)
{
	t_list		*command_list;
	t_list		*current;
	t_command	*command;
	t_token		*token;

	command_list = NULL;
	if (!msh->tokens)
		return (NULL);
	current = msh->tokens;
	while (current)
	{
		token = (t_token *) current->content;
		command = parser_command_new(msh, ft_strdup_safe(msh, token->value));
		command->args = parser_get_arguments(current, msh);
		command->redirect_in = redirect_get_inputs(msh, current);
		command->redirect_out = redirect_get_outputs(msh, current);
		if (!validate_redirects(command->redirect_in))
		{
			break ;
		}
		ft_lstadd_back(&command_list, ft_lstnew_safe(msh, command));
		while (current && is_command_token((t_token *)current->content))
			current = current->next;
		if (current && ((t_token *)current->content)->type >= 3)
			current = current->next;
	}
	ft_lstiter(command_list, print_commands);
	return (command_list);
}
