/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   checkers.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: tchampio <tchampio@student.42lehavre.fr>   +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/06/21 19:29:45 by tchampio          #+#    #+#             */
/*   Updated: 2025/06/21 19:32:04 by tchampio         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../../includes/maputils.h"
#include "../../includes/libft.h"

bool	check_filename(t_mapdata *map, char *file)
{
	int		filename_size;
	int		i;
	int		j;
	char	end[5];

	filename_size = ft_strlen(file);
	i = filename_size;
	j = 4;
	ft_bzero(end, 5);
	while (i > (filename_size - 5))
	{
		end[j] = file[i];
		i--;
		j--;
	}
	if (ft_strncmp(end, ".cub", 5))
		return (false);
	map->filename = ft_strdup(file);
	return (true);
}

void	populate_maps(t_mapdata *map, int fd)
{
	char	*line;

	line = get_next_line(fd);
	while (line)
	{
		if (line[0] != '\n')
			add_map_line(line, map);
		free(line);
		line = get_next_line(fd);
	}
	free(line);
}

bool	check_walls(t_mapdata *map)
{
	int		i;
	int		j;

	i = 0;
	while (i < map->mapheight)
	{
		j = 0;
		while (map->map[i][j] == ' ')
			j++;
		if (map->map[i][j] != '1'
			&& map->map[i][ft_strlen(map->map[i]) - 1] != '1')
			return (false);
		if (i == 0 || i == map->mapheight - 1)
		{
			while (map->map[i][j] == '1' || map->map[i][j] == ' '
				|| map->map[i][j] == '\n')
				j++;
			if (ft_strlen(map->map[i]) != (unsigned int)j)
				return (false);
		}
		if (has_forbidden_characters(map->map[i]))
			return (false);
		i++;
	}
	return (true);
}

bool	check_bare_minimum(t_mapdata *map)
{
	int		i;
	int		spawncount;
	int		j;

	i = 0;
	spawncount = 0;
	while (map->map[i])
	{
		j = 0;
		while (map->map[i][j])
		{
			if (map->map[i][j] == 'N' || map->map[i][j] == 'E'
				|| map->map[i][j] == 'S' || map->map[i][j] == 'W')
			{
				spawncount++;
				map->startx = j;
				map->starty = i;
			}
			j++;
		}
		i++;
	}
	if (spawncount == 1)
		return (true);
	return (false);
}

bool	has_forbidden_characters(char *line)
{
	static const char	*allowedchars = " 10NSEW\n";
	size_t				strsize;
	int					i;

	strsize = ft_strlen(line);
	i = 0;
	while (i < (int)strsize)
	{
		if (!ft_strchr(allowedchars, line[i]))
			return (true);
		i++;
	}
	return (false);
}
