/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_str_case.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pbonilla <eirodeis.lepnj@gmail.com>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/03/04 05:25:41 by pbonilla          #+#    #+#             */
/*   Updated: 2021/03/19 19:18:42 by pbonilla         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../includes/ft_printf.h"

char			*fill_s_str(char *s, int len, char *s_arg, t_param *param)
{
	int			i;

	i = ft_strlen(s_arg);
	if (param->prec != -1 && param->prec < i)
		i = param->prec;
	while (--len >= 0 && --i >= 0)
		s[len] = s_arg[i];
	return (s);
}

void			change_par_str(t_param *param)
{
	if (param->width < 0 && param->width != -1)
	{
		param->width *= -1;
		param->minus = 1;
	}
	if (param->prec < -1)
		param->prec = -1;
}

char			*ft_str_case(t_param *param, char *str)
{
	int			save;
	int			len;
	char		*s_arg;
	char		*s;

	change_par_str(param);
	s_arg = str;
	if (!str)
		s_arg = ft_strdup("(null)");
	len = ft_strlen(s_arg);
	if (param->prec != -1 && param->prec < len)
		len = param->prec;
	save = len;
	if (param->width > len)
		len = param->width;
	if (!(s = malloc(sizeof(char) * len + 1)))
		return (NULL);
	s[len] = 0;
	ft_printf_memset(s, len, param);
	if (param->minus)
		len = save;
	s = fill_s_str(s, len, s_arg, param);
	if (!str)
		free(s_arg);
	return (s);
}