/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   valid_command.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/10/24 18:52:05 by lperrey           #+#    #+#             */
/*   Updated: 2021/10/24 19:21:28 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

int			valid_io_redirect(t_token **token_list);

static int	valid_command_rule1(t_token **token_list);
static int	valid_command_rule2(t_token **token_list);
static int	valid_command_rule3(t_token **token_list);
static int	valid_command_rule4(t_token **token_list);

int	valid_command(t_token **token_list)
{
	t_token	*cmd_start;

	cmd_start = *token_list;
	if (valid_command_rule1(token_list))
		return (1);
	*token_list = cmd_start;
	if (valid_command_rule2(token_list))
		return (1);
	*token_list = cmd_start;
	if (valid_command_rule3(token_list))
		return (1);
	*token_list = cmd_start;
	if (valid_command_rule4(token_list))
		return (1);
	return (0);
}

// cmd_prefix cmd_name cmd_suffix
static int	valid_command_rule1(t_token **token_list)
{
	while (valid_io_redirect(token_list))
	{
		if (valid_token(token_list, T_WORD))
		{
			while (valid_token(token_list, T_WORD)
				|| valid_io_redirect(token_list))
			{
				if (valid_command_separator(*token_list))
					return (1);
			}
		}
	}
	return (0);
}

// cmd_prefix cmd_name
static int	valid_command_rule2(t_token **token_list)
{
	while (valid_io_redirect(token_list))
	{
		if (valid_token(token_list, T_WORD))
		{
			if (valid_command_separator(*token_list))
				return (1);
		}
	}
	return (0);
}

// cmd_name cmd_suffix
static int	valid_command_rule3(t_token **token_list)
{
	if (valid_token(token_list, T_WORD))
	{
		while (valid_token(token_list, T_WORD) || valid_io_redirect(token_list))
		{
			if (valid_command_separator(*token_list))
				return (1);
		}
	}
	return (0);
}

// cmd_name
static int	valid_command_rule4(t_token **token_list)
{
	if (valid_token(token_list, T_WORD))
	{
		if (valid_command_separator(*token_list))
			return (1);
	}
	return (0);
}
