/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parsing.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/01/05 20:14:44 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/16 18:48:43 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "solong.h"

int	ft_test_map_dimmention(t_map *map)
{
	size_t	i;
	size_t	len;

	len = ft_strlen(map->patern[0]);
	i = 1;
	while (map->patern[i] != NULL)
	{
		if (ft_strlen(map->patern[i]) != len)
			return (0);
		i++;
	}
	map->x_len = len;
	map->y_len = i;
	return (1);
}

int	ft_test_map_content1(t_map *map)
{
	size_t	x;
	size_t	y;
	size_t	nb_collectable;

	nb_collectable = 0;
	y = 0;
	while (y < map->y_len)
	{
		x = 0;
		while (x < map->x_len)
		{
			if (ft_is_in("01CEPB", map->patern[y][x]) == 0)
				return (0);
			if (map->patern[y][x] == 'C')
				nb_collectable++;
			x++;
		}
		y++;
	}
	if (nb_collectable == 0)
		return (0);
	map->nb_collectable = nb_collectable;
	return (1);
}

int	ft_test_map_content2(char **patern)
{
	size_t	x;
	size_t	y;
	size_t	test1;
	size_t	test2;

	test1 = 0;
	test2 = 0;
	y = 0;
	while (patern[y + 1] != NULL)
	{
		x = 0;
		while (x < ft_strlen(patern[y]))
		{
			if (patern[y][x] == 'E')
				test1++;
			else if (patern[y][x] == 'P')
				test2++;
			x++;
		}
		y++;
	}
	return (test1 == 1 && test2 == 1);
}

int	ft_test_map_is_surronded(t_map map)
{
	size_t	i;

	if (!ft_contain_only(map.patern[0], '1'))
		return (0);
	i = 1;
	while (map.patern[i + 1] != NULL)
	{
		if (map.patern[i][0] != '1')
			return (0);
		if (map.patern[i][ft_strlen(map.patern[i]) - 1] != '1')
			return (0);
		i++;
	}
	if (!ft_contain_only(map.patern[i], '1'))
		return (0);
	return (1);
}

int	ft_map_is_correct(t_map *map)
{
	if (!ft_test_map_dimmention(map))
		return (0);
	if (!ft_test_map_content1(map))
		return (0);
	if (!ft_test_map_content2(map->patern))
		return (0);
	if (!ft_test_map_dimmention(map))
		return (0);
	if (!ft_test_map_is_surronded(*map))
		return (0);
	if (!ft_test_map_is_finishable(map))
		return (0);
	return (1);
}
