#include "push_swap.h"

/*
** this function is called by actions like sa()
** it fills a new str element on the chained list like this :
**
**   b: nbb3 nbb2 nbb1!a: nba5 nba4 nba3 nba2 nba1!name
** (it fills it by the end, "!name" first, then "nba1" on its back, and so on)
**
** so it can later be printed like that (in case of flag -p) :
** the "!" split the str :
**
**   [0]b: nbb3 nbb2 nbb1 [1]a: nba5 nba4 nba3 nba2 nba1 [2]name
**
** to produce :
**
**   [2]name
**   [1]     a: nba5 nba4 nba3 nba2 nba1
**   [0]     b: nbb3 nbb2 nbb1
**
** (if no flag -p, only [2]name is displayed)
*/
void	fill_solution(t_list *solution, char *sp)
{
	t_stack	*a;
	t_stack	*b;
	char	*stack;

	a = *(t_stack **)(solution->content);
	b = *(t_stack **)(solution->next->content);
	stack = ft_strjoinfree(ft_strdup("!"), ft_strdup(sp));
	while (a != NULL)
	{
		stack = ft_strjoinfree(ft_itoa(a->n), stack);
		stack = ft_strjoinfree(ft_strdup(" "), stack);
		a = a->next;
	}
	stack = ft_strjoinfree(ft_strdup("!a:"), stack);
	while (b != NULL)
	{
		stack = ft_strjoinfree(ft_itoa(b->n), stack);
		stack = ft_strjoinfree(ft_strdup(" "), stack);
		b = b->next;
	}
	stack = ft_strjoinfree(ft_strdup("b:"), stack);
	ft_lstadd_back(&solution, ft_lstnew(stack));
}

void	print_result(t_list *result, int flag)
{
	int		i;
	char	**part;

	i = -1;
	result = result->next->next;
	while (result)
	{
		i++;
		part = ft_split(result->content, '!');
		ft_printf("%s\n", part[2]);
		if (flag)
		{
			ft_printf("     %s\n", part[1]);
			ft_printf("     %s\n", part[0]);
		}
		result = result->next;
		free(part[0]);
		free(part[1]);
		free(part[2]);
		free(part);
	}
	if (flag)
		ft_putnbrendl(i);
}
