/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   game.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/04/15 15:46:08 by qmennen           #+#    #+#             */
/*   Updated: 2025/06/11 17:44:59 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "game.h"

int	game_create(t_game **game)
{
	*game = malloc(sizeof(t_game));
	if (!game)
		return (FAILURE);
	ft_memset(*game, 0, sizeof(t_game));
	(*game)->fps = 20;
	(*game)->scoreboard = malloc(sizeof(t_scoreboard));
	ft_memset((*game)->scoreboard, 0, sizeof(t_scoreboard));
	if (!(*game)->scoreboard)
	{
		return (free(*game), FAILURE);
	}
	return (SUCCESS);
}

void	game_over(t_game_manager *manager)
{
	t_game	*game;

	game = manager->game;
	game->screen->hud->instances[0].enabled = false;
	game->screen->minimap->instances[0].enabled = false;
	game->screen->img->instances[0].enabled = false;
	game->scoreboard->end_time = mlx_get_time();
	manager->state = GAME_STATE_END_SCREEN;
	manager->active_menu = &manager->end_screen;
	set_uniforms(game);
}

void	game_run(t_game *game)
{
	static int	fps = 0;

	fps += (int)(1.f / game->screen->mlx->delta_time);
	set_uniforms(game);
	player_update(game, game->screen->mlx->delta_time);
	cast_rays(game);
	update_monsters(game);
	render_map(game);
	handle_battery(game);
	handle_record(game);
	handle_mouse(game);
	collision_sprite(game, 0, 0);
	if (game->player->battery <= 0 || count_tiles(game->map, TILE_EMPTY) == 0)
		game_over(game->manager);
}

void	game_free(t_game *game)
{
	if (game->scoreboard)
		free(game->scoreboard);
	if (game->screen)
		free(game->screen);
	if (game->player)
		free(game->player);
	if (game->map)
		map_free(game->map);
	if (game->keyboard)
		free(game->keyboard);
	game->scoreboard = NULL;
	free(game);
}
