/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   expander_parse_variables.c                         :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/19 13:58:13 by qmennen       #+#    #+#                 */
/*   Updated: 2025/02/26 17:41:14 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static char	*ft_itoa_safe(t_minishell *msh, int n)
{
	char	*str;

	str = ft_itoa(n);
	check_malloc(msh, str);
	return (str);
}

static t_list	*create_exit_status_env(t_minishell *msh)
{
	t_environment	*env;

	env = malloc_safe(msh, sizeof(t_environment));
	env->name = ft_strdup_safe(msh, "?");
	env->value = ft_itoa_safe(msh, msh->exit_status);
	return (ft_lstnew_safe(msh, env));
}

t_list	*expander_parse_variables(const char *s, t_minishell *msh)
{
	int				i;
	t_list			*var_list;
	t_environment	*env;

	i = 0;
	var_list = NULL;
	while (s[i])
	{
		if (s[i] == '$')
		{
			env = expander_get_var(s, i + 1, msh);
			if (env)
				ft_lstadd_back(&var_list, ft_lstnew_safe(msh, env));
			else
			{
				if (s[i + 1] == '?')
					ft_lstadd_back(&var_list, create_exit_status_env(msh));
				else
					ft_lstadd_back(&var_list, ft_lstnew_safe(msh, NULL));
			}
		}
		i++;
	}
	return (var_list);
}
