/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_arglist_bonus.c                                 :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/27 17:04:47 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:07:39 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../libft.h"
#include "ft_printf.h"
#include "ft_printf_bonus.h"

static void	ft_set_default_flag_values(t_arglist *arglist)
{
	arglist->width_mini = 0;
	arglist->precision = -1;
	arglist->flag_hashtag = 0;
	arglist->flag_zero = 0;
	arglist->flag_justified_left = 0;
	arglist->flag_space = 0;
	arglist->flag_plus = 0;
}

static void	ft_handle_overriding_arguments(t_arglist *arglist)
{
	if ((arglist->precision >= 0) || arglist->flag_justified_left)
		arglist->flag_zero = 0;
	if (arglist->flag_plus)
		arglist->flag_space = 0;
}

static void	ft_handle_width_precision(
t_arglist *arglist,
int *i,
const char *str,
va_list *args)
{
	if (ft_isdigit(str[*i]))
	{
		arglist->width_mini = ft_atoi(&str[*i], NULL);
		while (ft_isdigit(str[*i]))
			(*i)++;
	}
	else if (str[*i] == '*')
	{
		arglist->width_mini = va_arg(*args, int);
		(*i)++;
	}
	if (str[*i] == '.')
	{
		(*i)++;
		if (str[*i] == '*')
		{
			arglist->precision = va_arg(*args, int);
			(*i)++;
		}
		else
			arglist->precision = ft_atoi(&str[*i], NULL);
		while (ft_isdigit(str[*i]))
			(*i)++;
	}
}

static void	ft_handle_flags(t_arglist *arglist, int *i, const char *str)
{
	while (str[*i] == '#' || str[*i] == '0' || str[*i] == '-'
		|| str[*i] == ' ' || str[*i] == '+')
	{
		if (str[*i] == '#')
			arglist->flag_hashtag = 1;
		if (str[*i] == '0')
			arglist->flag_zero = 1;
		if (str[*i] == '-')
			arglist->flag_justified_left = 1;
		if (str[*i] == ' ')
			arglist->flag_space = 1;
		if (str[*i] == '+')
			arglist->flag_plus = 1;
		(*i)++;
	}
}

t_arglist	*ft_create_arglist(const char *str, va_list *args)
{
	t_arglist	*arglist;
	int			i;

	arglist = malloc(sizeof(t_arglist));
	if (!arglist)
		return (NULL);
	ft_set_default_flag_values(arglist);
	i = 0;
	if (str[i] == '%')
		i++;
	ft_handle_flags(arglist, &i, str);
	ft_handle_width_precision(arglist, &i, str, args);
	arglist->size_of_argument_string = i;
	ft_handle_overriding_arguments(arglist);
	return (arglist);
}
