/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   game.c                                             :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/04/15 15:46:08 by qmennen       #+#    #+#                 */
/*   Updated: 2025/05/23 15:58:12 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "cub3d.h"
#include "glad.h"
#include "MLX42_Int.h"

int	game_create(t_game **game)
{
	*game = malloc(sizeof(t_game));
	if (!game)
		return (FAILURE);
	memset(*game, 0, sizeof(t_game));
	(*game)->fps = 20;
	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;
	static int	fps = 0;

	game = (t_game *)param;
	game->framecount++;
	fps += (int)(1.f / game->screen->mlx->delta_time);
	set_uniforms(game);
	if (game->framecount % 20 == 0)
	{
		game->fps = (int)(fps / 20);
		fprintf(stderr, "battery: %f  FPS: %d\n",game->player->battery, fps / 20);
		fps = 0;
	}
	player_update(game, game->screen->mlx->delta_time);
	cast_rays(game);
	render_map(game);
	keyboard_update(game);
	if (game->player->is_moving)
	{
		game->screen->img->instances[0].x = sin(game->framecount / 6.0) * 20;
		game->screen->img->instances[0].y = cos(game->framecount / 3.0) * 10;
	}
	game->player->battery -= game->screen->mlx->delta_time / 10;
	if (game->player->battery < 0)
		game->player->battery = 0.001f;
}

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);
}
