#include "redirection_private.h"

int	ft_replace_file(t_data *data, char **tab)
{
	size_t	i;
	char	*redirection;

	i = 0;
	while (tab[i] != NULL)
	{
		if (ft_is_in("<>", tab[i][0]))
		{
			i++;
			redirection = ft_env_filler(data, tab[i]);
			if (redirection == NULL)
				return (1);
			free(tab[i]);
			tab[i] = redirection;
			ft_quote_remover(tab[i]);
		}
		i++;
	}
	return (0);
}

void	ft_remove_redirection(char *cmd_str)
{
	size_t	i;
	ssize_t	start;
	ssize_t	stop;

	i = 0;
	while (cmd_str[i] != '\0')
	{
		start = -1;
		while ((ft_is_in_quote(cmd_str, i) || !ft_is_in("<>", cmd_str[i]))
			&& cmd_str[i] != '\0')
			i++;
		if (ft_is_in("<>", cmd_str[i]))
			start = i;
		if (start == -1)
			continue ;
		while (cmd_str[i] == cmd_str[start])
			i++;
		while (cmd_str[i] == ' ')
			i++;
		while (cmd_str[i] != '\0' && (cmd_str[i] != ' ' || ft_is_in_quote(cmd_str, i)))
			i++;
		stop = i - start;
		if (start != -1)
		{
			ft_strshift(cmd_str + start, -1 * stop);
			i = start;
		}
	}
}

int	ft_set_redirection(t_data *data, t_cmd *cmd, char **tab)
{
	size_t	i;

	i = 0;
	while (tab[i + 1] != NULL)
	{
		ft_quote_remover(tab[i + 1]);
		if (ft_strcmp(tab[i], "<<") == 0)
		{
			cmd->fd_in[0] = ft_heredoc(data, tab[i + 1]);
			if (cmd->fd_in[0] == -2)
				return (1);
		}
		else if (ft_strcmp(tab[i], "<") == 0)
		{
			if (ft_file_is_readable(data, tab[i + 1]))
				cmd->fd_in[0] = open(tab[i + 1], O_RDONLY);
			else
				return (1);
		}
		else if(ft_strcmp(tab[i], ">") == 0)
		{
			if (ft_file_is_writable(data, tab[i + 1]))
				cmd->fd_out[0] = open(tab[i + 1], O_WRONLY | O_TRUNC | O_CREAT, 0644);
			else
				return (1);
		}
		else if(ft_strcmp(tab[i], ">>") == 0)
		{
			if (ft_file_is_appendable(data, tab[i + 1]))
				cmd->fd_out[0] = open(tab[i + 1], O_WRONLY | O_APPEND | O_CREAT, 0644);
			else
				return (1);
		}
		i++;
	}
	return (0);
}

int	ft_redirection(t_data *data, t_cmd *cmd, char *cmd_str)
{
	char	**tab;

	cmd->fd_in[0] = -1;
	cmd->fd_in[1] = -1;
	cmd->fd_out[0] = -1;
	cmd->fd_out[1] = -1;
	tab = ft_split_quoted(cmd_str, ' ');
	if (tab == NULL)
	{
		ft_eprintf("minishell: malloc failed\n");
		return (1);
	}
	ft_remove_redirection(cmd_str);
	if (ft_set_redirection(data, cmd, tab))
	{
		ft_freer_tab_ultimate(1, tab);
		return (1);
	}
	ft_freer_tab_ultimate(1, tab);
	return (0);
}
