/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   check_map_content.c                                :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:04:44 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 13:05:34 by pblagoje         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static int	set_player(t_map *map, int y, int x, char dir)
{
	map->plr_x = x;
	map->plr_y = y;
	map->content[y][x] = '0';
	map->plr_dir = dir;
	return (1);
}

void	set_points(int *y, int *x, int row, int col)
{
	y[0] = row - 1;
	y[1] = row;
	y[2] = row + 1;
	x[0] = col - 1;
	x[1] = col;
	x[2] = col + 1;
}

int	check_spaces(t_map *map, int row, int col)
{
	int	y[3];
	int	x[3];
	int	i;
	int	j;

	set_points(y, x, row, col);
	i = 0;
	while (i < 3)
	{
		j = 0;
		while (j < 3)
		{
			if (y[i] > 0 && y[i] < map->size_y - 1 \
				&& x[j] > 0 && x[j] < map->size_x - 1)
			{
				if (map->content[y[i]][x[j]] != '1' \
					&& map->content[y[i]][x[j]] != ' ')
					return (EXIT_FAILURE);
			}
			j++;
		}
		i++;
	}
	return (EXIT_SUCCESS);
}

int	check_content(t_map *map)
{
	int	x;
	int	y;
	int	count;

	count = 0;
	y = 0;
	while (map->content[y] != NULL)
	{
		x = 0;
		while (map->content[y][x] != '\0' && map->content[y][x] != '\n')
		{
			if (map->content[y][x] == ' ' && check_spaces(map, y, x))
				mb_exit("Error\nInvalid space positions.\n", EXIT_FAILURE);
			else if (!ft_strchr(" .01SNWE", map->content[y][x]))
				mb_exit("Error\nInvalid map characters.\n", EXIT_FAILURE);
			else if (ft_strchr("SNWE", map->content[y][x]) \
					&& set_player(map, y, x, map->content[y][x]))
				count++;
			x++;
		}
		y++;
	}
	if (count != 1)
		mb_exit("Error\nToo many player starting positions.\n", EXIT_FAILURE);
	return (EXIT_SUCCESS);
}
