/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   env_fill.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angoulem      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/02/16 16:29:08 by cchauvet          #+#    #+#             */
/*   Updated: 2023/02/20 15:39:28 by starnakin        ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "./env_private.h"
#include "env.h"

static char	*ft_getkey(const char *str)
{
	size_t	i;
	char	*key;

	if (ft_strncmp(str, "$$", 2) == 0)
		key = ft_strdup("$");
	else if (ft_strncmp(str, "$?", 2) == 0)
		key = ft_strdup("?");
	else if (str[1] == '\0')
		key = ft_strdup("");
	else
	{
		i = 1;
		while (str[i] != '\0' && !ft_is_in("$?\'\"", str[i]))
			i++;
		key = ft_strndup(str + 1, i - 1);
	}
	if (key == NULL)
		ft_eprintf("minishell: malloc failed\n");
	return (key);
}

static char	*ft_getvalue(t_data *data, char *key)
{
	char	*value;

	if (ft_strcmp(key, "?") == 0)
		value = ft_itoa(data->exit_code);
	else if (ft_strcmp(key, "$") == 0)
		value = ft_strdup("PID");
	else if (key[0] == '\0')
		value = ft_strdup("$");
	else
	{
		value = get_value_by_key(key, data->env);
		if (value == NULL)
			value = ft_strdup("");
		else
			value = ft_strdup(value);
	}
	if (value == NULL)
		ft_eprintf("minishell: malloc failed\n");
	return (value);
}

static char	*ft_getvalue_by_str(t_data *data, const char *str,
		size_t	*key_len)
{
	char	*key;
	char	*value;

	key = ft_getkey(str);
	if (key == NULL)
		return (NULL);
	*key_len = ft_strlen(key) + 1;
	value = ft_getvalue(data, key);
	free(key);
	return (value);
}

char	*ft_env_filler(t_data *data, const char *str)
{
	char	*out;
	char	*temp;
	char	*value;
	size_t	key_len;
	size_t	i;

	out = ft_strdup(str);
	if (out == NULL)
		return (NULL);
	i = 0;
	while (out[i] != '\0')
	{
		while (ft_is_in_quote(out, i) == 1)
			i++;
		while (out[i] == '$')
		{
			value = ft_getvalue_by_str(data, out + i, &key_len);
			if (value == NULL)
				return (NULL);
			temp = ft_strreplace(out, value, i, key_len + i);
			i = i + ft_strlen(value);
			free(out);
			free(value);
			if (temp == NULL)
				return (NULL);
			out = temp;
		}
		i++;
	}
	return (out);
}
