/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   fill_token.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/10/19 08:38:55 by lperrey           #+#    #+#             */
/*   Updated: 2021/12/01 16:00:48 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

int			check_operators(t_token *t, char *input, int *i, int *t_i);

static int	quoting(int *quotes_state, char *input, int *i);

int	fill_token(t_token *t, char *input, int *i, int *t_i)
{
	static int	quotes_state = 0;

	if (!quotes_state)
	{
		if (check_operators(t, input, i, t_i) == DELIMITE_TOKEN)
			return (DELIMITE_TOKEN);
	}
	if (quoting(&quotes_state, input, i))
	{
		t->content[(*t_i)++] = input[(*i)++];
		return (CONTINUE_TOKEN);
	}
	if (!quotes_state && (input[*i] == ' ' || input[*i] == '\t'))
	{
		while (input[*i] == ' ' || input[*i] == '\t')
			(*i)++;
		return (DELIMITE_TOKEN);
	}
	else
		t->content[(*t_i)++] = input[(*i)++];
	return (CONTINUE_TOKEN);
}

static int	quoting(int *quotes_state, char *input, int *i)
{
	if (input[*i] == '\'' && *quotes_state != IN_DQUOTES)
	{
		if (*quotes_state == IN_QUOTES)
			*quotes_state = 0;
		else if (ft_strchr(&input[*i + 1], '\''))
			*quotes_state = IN_QUOTES;
		return (CONTINUE_TOKEN);
	}
	else if (input[*i] == '\"' && *quotes_state != IN_QUOTES)
	{
		if (*quotes_state == IN_DQUOTES)
			*quotes_state = 0;
		else if (ft_strchr(&input[*i + 1], '\"'))
			*quotes_state = IN_DQUOTES;
		return (CONTINUE_TOKEN);
	}
	return (0);
}
