/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   cube3d.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:42:00 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 21:58:13 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

void	destroy_mlx(void *param)
{
	t_game	*game;

	game = param;
	if (game->fd != -1)
		close(game->fd);
	if (game->mlx_ptr == NULL)
		return ;
	if (game->img.ptr)
		mlx_destroy_image(game->mlx_ptr, game->img.ptr);
	if (game->txt.img_n.ptr)
		mlx_destroy_image(game->mlx_ptr, game->txt.img_n.ptr);
	if (game->txt.img_s.ptr)
		mlx_destroy_image(game->mlx_ptr, game->txt.img_s.ptr);
	if (game->txt.img_e.ptr)
		mlx_destroy_image(game->mlx_ptr, game->txt.img_e.ptr);
	if (game->txt.img_w.ptr)
		mlx_destroy_image(game->mlx_ptr, game->txt.img_w.ptr);
	if (game->win.ptr)
		mlx_destroy_window(game->mlx_ptr, game->win.ptr);
	mlx_destroy_display(game->mlx_ptr);
}

int	shut_down(void)
{
	mb_exit(B_RED"close windows"RESET"\n", EXIT_SUCCESS);
	return (0);
}

int	main(int ac, char **av)
{
	t_game	*game;

	if ((ac != 2 || check_extension(av[1], ".cub")) && \
		write(2, "Error\nPlease use a valid .cub file as single argument.\n", 53))
		return (EXIT_FAILURE);
	game = init_struct();
	mb_init(destroy_mlx, game);
	if (init_parsing(game, av[1]))
		return (EXIT_FAILURE);
	if (check_map(&(game->map)))
		return (EXIT_FAILURE);
	init_game(game);
	draw(game);
	mlx_hook(game->win.ptr, 2, 1L << 0, keypress, game);
	mlx_hook(game->win.ptr, 3, 1L << 1, keyrelease, game);
	mlx_hook(game->win.ptr, 17, 1L << 17, shut_down, NULL);
	mlx_loop_hook(game->mlx_ptr, hook_action, game);
	mlx_loop(game->mlx_ptr);
	return (0);
}
