/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parsing2.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/01/12 16:17:20 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/16 18:48:20 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "solong.h"

static void	ft_collector(char **patern, size_t x, size_t y)
{
	if (ft_is_in("1B", patern[y][x]))
		return ;
	patern[y][x] = '1';
	ft_collector(patern, x, y - 1);
	ft_collector(patern, x + 1, y);
	ft_collector(patern, x, y + 1);
	ft_collector(patern, x - 1, y);
}

static char	**ft_patern_dup(char **patern)
{
	char	**patern2;
	size_t	i;

	i = 0;
	while (patern[i] != NULL)
		i++;
	patern2 = ft_calloc(i + 1, sizeof(char *));
	if (patern2 == NULL)
		return (0);
	i = 0;
	while (patern[i] != NULL)
	{
		patern2[i] = ft_strdup(patern[i]);
		if (patern2[i] == NULL)
		{
			ft_cancel(patern2, i);
			return (NULL);
		}
		i++;
	}
	patern2[i] = NULL;
	return (patern2);
}

int	ft_test_map_is_finishable(t_map *map)
{
	size_t	i;
	int		ok;
	char	**patern;

	patern = ft_patern_dup(map->patern);
	if (patern == NULL)
		return (1);
	ft_fill_pos(map);
	ft_collector(patern, map->player_pos[0], map->player_pos[1]);
	i = 1;
	ok = 1;
	while (patern[i + 1] != NULL)
	{
		if (ft_is_in(patern[i], 'C') || ft_is_in(patern[i], 'E'))
			ok = 0;
		i++;
	}
	ft_freer_tab_ultimate(1, patern);
	return (ok);
}
