/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   lexer_token_next.c                                 :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/04 16:07:58 by qmennen       #+#    #+#                 */
/*   Updated: 2025/02/26 16:14:10 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static t_token_type	get_word_type(char c)
{
	if (c == '\'')
		return (T_SQWORD);
	else if (c == '"')
		return (T_DQWORD);
	else
		return (T_WORD);
}

static t_token	*	process_word(t_minishell *msh, t_lexer *lexer, int pos)
{
	t_token_type	word_type;
	t_token			*token;
	char			*word;

	word_type = get_word_type(lexer->current_char);
	word = lexer_readword(msh, lexer);
	if (!word)
	{
		return (token_new(msh, T_ERROR, &(lexer->current_char), pos));
	}
	token = token_new(msh, word_type, word, pos);
	free_safe(msh, (void **)&word);
	return (token);
}

/**
 * @brief Retrieves the next token from the lexer.
 *
 * This function reads the next token from the lexer, skipping any whitespace
 * characters. It handles different types of tokens such as end-of-file (EOF),
 * special characters ('<', '>', '|'), printable characters, and errors.
 *
 * @param lexer A pointer to the lexer structure.
 * @return A pointer to the newly created token.
 *
 * The function performs the following steps:
 * 1. Skips any whitespace characters.
 * 2. Checks the current character in the lexer:
 *    - If it is the end-of-file character ('\0'), creates an EOF token.
 *    - If it is a special character ('<', '>', '|'), parses
 * 		the token accordingly.
 *    - If it is a printable character, reads the word and creates a word token.
 *    - Otherwise, creates an error token.
 */
t_token	*ft_token_next(t_minishell *msh, t_lexer *lexer)
{
	t_token			*token;
	int				current_pos;
	char			c;

	token = NULL;
	while (ft_isspace(lexer->current_char))
		lexer_readchar(lexer);
	current_pos = lexer->pos;
	c = lexer->current_char;
	if (c == '\0')
		token = token_new(msh, T_EOF, NULL, current_pos);
	else if (c == '<' || c == '>'
		|| c == '|')
		token = token_parse(msh, lexer);
	else if (ft_isprint(lexer->current_char))
		token = process_word(msh, lexer, current_pos);
	else
		token = token_new(msh, T_ERROR, NULL, current_pos);
	c = lexer->current_char;
	return (token);
}
