/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: tchampio <tchampio@student.42lehavre.      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/05/06 13:16:11 by tchampio          #+#    #+#             */
/*   Updated: 2025/06/16 16:12:50 by tchampio         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../includes/libft.h"
#include "../includes/cub3d_consts.h"
#include "../mlx/mlx.h"
#include "../includes/maputils.h"
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>

typedef struct s_mlx_data
{
	void	*img;
	char	*addr;
	int		bits_per_pixel;
	int		line_length;
	int		endian;
}	t_mlx_data;


void	my_mlx_pixel_put(t_mlx_data *data, int x, int y, int color)
{
	char	*dst;

	dst = data->addr + (y * data->line_length + x * (data->bits_per_pixel / 8));
	*(unsigned int*)dst = color;
}

int	destroy(t_mapdata *map)
{
	(void)map;
	exit(0);
	return 0;
}

int	key_destroy(int keycode, t_mapdata *map)
{
	if (keycode == 65307)
		destroy(map);
	return (0);
}

int	main(int argc, char **argv)
{
	void		*mlx;
	void		*mlx_win;
	char		*xpm = "./ressources/test.xpm";
	void		*xpm_image;
	int		xpm_height;
	int		xpm_width;
	t_mlx_data	data;
	t_mapdata	map;

	ft_bzero(&map, sizeof(map));
	if (argc < 2)
		return (ft_printf("Error: Missing cub3d file\n"), 1);
	if (!check_cubfile(argv[1], &map))
		return (ft_printf("Error: Wrong map file. Reason: %s\n", map.error), 1);
	mlx = mlx_init();
	mlx_win = mlx_new_window(mlx, 800, 600, "Cub3d");
	data.img = mlx_new_image(mlx, 800, 600);
	data.addr = mlx_get_data_addr(data.img, &data.bits_per_pixel, &data.line_length, &data.endian);
	xpm_image = mlx_xpm_file_to_image(mlx, xpm, &xpm_width, &xpm_height);
	//my_mlx_pixel_put(&data, 5, 5, 0x00FF0000);
	mlx_hook(mlx_win, 17, 0L, destroy, &map);
	mlx_key_hook(mlx_win, key_destroy, &map);
	mlx_put_image_to_window(mlx, mlx_win, data.img, 0, 0);
	mlx_put_image_to_window(mlx, mlx_win, xpm_image, 0, 0);
	mlx_loop(mlx);
}
