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

#include "cub3d.h"

static void	cut_image(t_screen *screen, mlx_image_t **canvas)
{
	unsigned int	i;
	unsigned int	j;
	unsigned int	idx1;
	unsigned int	idx2;

	i = 0;
	while (i < screen->height / 3)
	{
		j = 0;
		while (j < screen->width / 3)
		{
			idx1 = (i * screen->width / 3 + j) * 4;
			idx2 = (i * screen->img->width + j) * 12;
			(*canvas)->pixels[idx1] = screen->img->pixels[idx2];
			(*canvas)->pixels[idx1 + 1] = screen->img->pixels[idx2 + 1];
			(*canvas)->pixels[idx1 + 2] = screen->img->pixels[idx2 + 2];
			(*canvas)->pixels[idx1 + 3] = screen->img->pixels[idx2 + 3];
			j++;
		}
		i++;
	}
}

void	create_screenshot(t_game *game)
{
	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 ;
	cut_image(game->screen, &screenshot);
	game->screenshot_idx++;
	return ;
}

void	flash(t_game *game)
{
	mlx_image_t		*img;
	unsigned int	x;
	unsigned 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)
{
	unsigned 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);
}
