/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   game.c                                             :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/04/15 15:46:08 by qmennen       #+#    #+#                 */
/*   Updated: 2025/05/07 11:33:38 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "cub3d.h"

int	game_create(t_game **game)
{
	*game = malloc(sizeof(t_game));
	if (!game)
		return (FAILURE);
	(*game)->player = NULL;
	(*game)->map = NULL;
	(*game)->screen = NULL;
	(*game)->keyboard = NULL;
	return (SUCCESS);
}

void	free_game(t_game **game)
{
	if (game && *game)
	{
		if ((*game)->screen)
			free((*game)->screen);
		if ((*game)->player)
			free((*game)->player);
		if ((*game)->map)
			free((*game)->map);
		free(*game);
	}
}

void	game_loop(void *param)
{
	t_game		*game;
	double		delta_time;
	static int	framecount = 0;
	static int	fps = 0;

	framecount++;
	game = (t_game *)param;
	delta_time = game->screen->mlx->delta_time;
	fps += (int)(1.f / delta_time);
	if (framecount % 20 == 0)
	{
		fprintf(stderr, "FPS: %d\n", fps / 20);
		fps = 0;
	}
	render_clear(game->screen);
	player_update(game, delta_time);
	cast_rays(game);
	render_map(game->screen, game->map);
	render_entities(game);
	keyboard_update(game);
}

void	game_free(t_game *game)
{
	if (game->screen)
	{
		mlx_delete_image(game->screen->mlx, game->screen->img);
		mlx_close_window(game->screen->mlx);
		mlx_terminate(game->screen->mlx);
		free(game->screen);
	}
	if (game->player)
		free(game->player);
	if (game->map)
		map_free(game->map);
	if (game->keyboard)
		free(game->keyboard);
	free(game);
}

void	game_terminate(t_game *game)
{
	game_free(game);
	exit(EXIT_SUCCESS);
}
