/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   parser_get_arguments.c                             :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/11 16:20:09 by qmennen       #+#    #+#                 */
/*   Updated: 2025/02/26 16:14:14 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	count_cmds(t_list *list)
{
	int		cmds;
	t_list	*current;
	t_token	*token;

	cmds = 0;
	current = list;
	while (current)
	{
		token = ((t_token *)current->content);
		if (token->type >= 3)
			break ;
		cmds++;
		current = current->next;
	}
	return (cmds);
}

static int	parser_should_expand(t_list *value)
{
	t_token	*token;

	token = (t_token *)value->content;
	if (!token)
		return (0);
	return (token->type == T_DQWORD
		|| (token->type == T_WORD
			&& token->value[0] == '$'
			&& token->value[1]));
}

char	**parser_get_arguments(t_list *list, t_minishell *msh)
{
	t_list	*current;
	char	**args;
	int		cmds;
	int		i;

	cmds = count_cmds(list);
	args = malloc_safe(msh, (cmds + 1) * sizeof(char *));
	current = list;
	i = -1;
	while ((++i) < cmds && current)
	{
		if (parser_should_expand(current))
			args[i] = expander_parse_string(
					((t_token *)current->content)->value, msh);
		else if (((t_token *)current->content)->type == T_WORD
			|| ((t_token *)current->content)->type == T_SQWORD)
			args[i] = ft_strdup_safe(msh,
					((t_token *)current->content)->value);
		current = current->next;
	}
	args[i] = 0;
	return (args);
}
