/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_case_u_bonus.c                                  :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/25 17:07:14 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:07:49 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

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

int	padding_if_needed_before(
		t_arglist *arglist,
		char caller,
		size_t len,
		t_vector *vec);
int	padding_if_needed_after(
		t_arglist *arglist,
		char caller,
		size_t len,
		t_vector *vec);

static int	ft_handle_padding_precision_bonus(
t_vector *vec,
size_t size,
t_arglist *arglist,
int padding_length)
{
	if (padding_if_needed_before(arglist, 'u', padding_length, vec) < 0)
		return (0);
	while ((int)size++ < arglist->precision)
	{
		if (!ft_vector_pushback(vec, '0'))
			return (0);
	}
	size--;
	return (1);
}

// Plus and space flags have undefined behavior here
int	ft_case_u_bonus(t_vector *vec, va_list *args, t_arglist *arglist)
{
	char			*str_to_cat;
	int				size;
	unsigned int	nbr;
	int				padding_length;

	nbr = va_arg(*args, unsigned int);
	if (nbr == 0 && arglist->precision == 0)
		str_to_cat = ft_strdup("");
	else
		str_to_cat = ft_utoa(nbr);
	if (!str_to_cat)
		return (0);
	size = (int)ft_strlen(str_to_cat);
	if (size < arglist->precision)
		padding_length = arglist->precision;
	else
		padding_length = size;
	if (!ft_handle_padding_precision_bonus(vec, size, arglist, padding_length))
		return (free(str_to_cat), 0);
	if (!ft_vector_concat(vec, str_to_cat, size))
		return (free(str_to_cat), 0);
	if (padding_if_needed_after(arglist, 'u', padding_length, vec) < 0)
		return (free(str_to_cat), 0);
	return (free(str_to_cat), 1);
}
