/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   lexer_read_word.c                                  :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/05 19:03:47 by qmennen       #+#    #+#                 */
/*   Updated: 2025/02/26 16:13:59 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static char	*parse_quotes(t_minishell *msh, t_lexer *lexer)
{
	int		start;
	int		len;
	char	qc;
	char	*word;

	qc = lexer->current_char;
	word = NULL;
	lexer_readchar(lexer);
	start = lexer->pos;
	while (lexer->current_char != '\0' && lexer->current_char != qc)
		lexer_readchar(lexer);
	len = lexer->pos - start;
	word = malloc_safe(msh, sizeof(char) * len + 1);
	ft_strlcpy(word, lexer->input + start, len + 1);
	if (lexer->current_char == qc)
		lexer_readchar(lexer);
	else
	{
		free_safe(msh, (void **)&word);
		return (NULL);
	}
	return (word);
}

char	*lexer_readword(t_minishell *msh, t_lexer *lexer)
{
	int		start;
	int		len;
	char	*word;

	start = lexer->pos;
	if (lexer->current_char == '"' || lexer->current_char == '\'')
	{
		return (parse_quotes(msh, lexer));
	}
	while (ft_isprint(lexer->current_char) && lexer->current_char != '<'
		&& lexer->current_char != '>' && lexer->current_char != '|'
		&& lexer->current_char != '\0' && !ft_isspace(lexer->current_char)
		&& lexer->current_char != '"' && lexer->current_char != '\'')
	{
		lexer_readchar(lexer);
	}
	len = lexer->pos - start;
	word = malloc_safe(msh, sizeof(char) * len + 1);
	ft_strlcpy(word, lexer->input + start, len + 1);
	return (word);
}
