#include "push_swap.h"

char	*fill_line(t_stack *list, char *stack)
{
	while (list != NULL)
	{
		if (list->limit == 1)
			stack = ft_strjoinfree(ft_strdup("]"), stack);
		stack = ft_strjoinfree(ft_itoa(list->n), stack);
		stack = ft_strjoinfree(ft_strdup(" "), stack);
		list = list->next;
	}
	return (stack);
}

void	mark_step(t_list *solution, char *step)
{
	char	*line;

	while (solution->next != NULL)
		solution = solution->next;
	line = solution->content;
	line = ft_strjoinfree(line, ft_strdup("!"));
	line = ft_strjoinfree(line, ft_strdup(step));
	solution->content = line;
}

/*
** 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));
	stack = fill_line(a, stack);
	stack = ft_strjoinfree(ft_strdup("!a:"), stack);
	stack = fill_line(b, stack);
	stack = ft_strjoinfree(ft_strdup("b:"), stack);
	ft_lstadd_back(&solution, ft_lstnew(stack));
}

// some drafty code to print sublist with flag
void	print_flags(char **part, int flag)
{
	int	last_a;
	int	last_b;


	last_a = part[1][ft_strlen(part[1]) - 1];
	last_b = part[0][ft_strlen(part[0]) - 1];
	if (flag && part[3] != NULL)
		ft_printf(" ( %s )", part[3]);
	if (flag == 1 || (flag == 2 && part[3] != NULL))
	{
		ft_printf("\n     %s", part[1]);
		if (part[3] != NULL && last_a != ']')
			ft_putchar(']');
		ft_printf("\n     %s", part[0]);
		if (part[3] != NULL && last_b != ']' && last_b != ':')
			ft_putchar(']');
	}
}

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

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