/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   game_manager.c                                     :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/05/27 13:48:18 by qmennen           #+#    #+#             */
/*   Updated: 2025/06/04 18:52:53 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "game_manager.h"

t_game_manager	*game_manager_create(t_game *game, int state)
{
	t_game_manager	*manager;

	manager = malloc(sizeof(t_game_manager));
	if (!manager)
		return (NULL);
	manager->game = game;
	manager->menu = NULL;
	manager->state = state;
	game->manager = manager;
	return (manager);
}

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

	if (!manager || !manager->game)
		return ;
	game = manager->game;
	if (manager->state == GAME_STATE_MENU)
		menu_display(*(manager->active_menu), game->screen);
	else if (manager->state == GAME_STATE_PLAYING)
		game_run(game);
	else if (manager->state == GAME_STATE_END_SCREEN)
		draw_end_screen(manager, manager->end_screen);
}

void	game_manager_update(void *param)
{
	t_game_manager	*manager;

	manager = (t_game_manager *)param;
	game_manager_handle_input(manager);
	game_manager_display(manager);
	keyboard_update(manager->game);
}

void	game_manager_destroy(t_game_manager *manager)
{
	if (!manager)
		return ;
	if (manager->menu)
		menu_free(manager->menu, manager->game->screen);
	if (manager->end_screen)
		menu_free(manager->end_screen, manager->game->screen);
	print_scores(manager->game);
	if (manager->game)
		game_free(manager->game);
	mlx_close_window(manager->game->screen->mlx);
	mlx_terminate(manager->game->screen->mlx);
	free(manager->game->screen);
	free(manager->game);
	free(manager);
	exit(EXIT_SUCCESS);
}
