/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   render.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/04/15 16:28:10 by qmennen           #+#    #+#             */
/*   Updated: 2025/06/03 22:17:23 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cub3d.h"

void	create_screenshot(t_game *game)
{
	int			i;
	int			j;
	int 		idx1;
	int 		idx2;
	mlx_image_t	*screenshot;
	if (!game->screenshots[game->screenshot_idx % MAX_SCREENSHOTS])
	{
		game->screenshots[game->screenshot_idx % MAX_SCREENSHOTS] = mlx_new_image(game->screen->mlx, game->screen->width / 3, game->screen->height / 3);
		mlx_image_to_window(game->screen->mlx, game->screenshots[game->screenshot_idx % MAX_SCREENSHOTS], 1000, 250);
		game->screenshots[game->screenshot_idx % MAX_SCREENSHOTS]->instances[0].enabled = false;
	}
	screenshot = game->screenshots[game->screenshot_idx % MAX_SCREENSHOTS];
	if (!screenshot)
		return ;
	i = 0;
	while (i < game->screen->height / 3)
	{
		j = 0;
		while (j < game->screen->width / 3)
		{
			idx1 = (i * game->screen->width / 3  + j) * 4;
			idx2 = (i * game->screen->img->width + j) * 12;
			screenshot->pixels[idx1] = game->screen->img->pixels[idx2];
			screenshot->pixels[idx1 + 1] = game->screen->img->pixels[idx2 + 1];
			screenshot->pixels[idx1 + 2] = game->screen->img->pixels[idx2 + 2];
			screenshot->pixels[idx1 + 3] = game->screen->img->pixels[idx2 + 3];
			j++;
		}
		i++;
	}
	printf("Screenshot %d taken\n", game->screenshot_idx);

	game->screenshot_idx++;
	return ;
}
void	flash(t_game *game)
{
	mlx_image_t		*img;
	int				x;
	int				y;

	if (game->screen->flash == 0)
		return ;
	img = game->screen->img;
	if (game->screen->flash == 2)
		create_screenshot(game);
	x = 0;
	while (x < img->width)
	{
		y = 0;
		while (y < img->height)
		{
			mlx_put_pixel(img, x, y, 0xffffffff);
			y++;
		}
		x++;
	}
	game->screen->flash--;
}

void	cast_rays(t_game *game)
{
	int			x;
	t_render	render[WIDTH];

	x = 0;
	draw_floor(game);
	while (x < game->screen->width)
	{
		render[x] = cast_ray(game, x);
		draw_line(game, render[x], x);
		x++;
	}
	render_sprites(render, game);
	flash(game);
}
