/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   render.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: erey-bet <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/12/29 18:06:42 by erey-bet          #+#    #+#             */
/*   Updated: 2023/01/06 15:40:33 by erey-bet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../so_long.h"

static void	*assets(t_data *data, int x, int y)
{
	int		dist;
	char	c;

	c = data->map[y][x];
	dist = sqrt(pow(x - data->x_ply, 2) + pow(y - data->y_ply, 2)) - 1;
	if (dist > 2)
		dist = 2;
	else if (c == '1')
		return (data->imgs.wall[dist]);
	else if (c == 'C')
		return (data->imgs.col[dist]);
	else if (c == 'E')
		return (data->imgs.exit[dist]);
	return (data->imgs.bg);
}

void	mpi(t_data *data, void *img, int x, int y)
{
	mlx_put_image_to_window(data->mlx, data->mlx_win, img, x, y);
}

void	draw_player(t_data *data, int xyhw[4])
{
	if (has_element(data->map, 'C'))
		mpi(data, data->imgs.ply[(xyhw[0] + xyhw[1]) % 4], xyhw[3], xyhw[2]);
	else
		mpi(data, data->imgs.ply[((xyhw[0] + xyhw[1]) % 4) + 4],
			xyhw[3], xyhw[2]);
}

void	draw(t_data *data, int xyhw[4])
{
	while (xyhw[1] < -1)
		xyhw[1]++;
	if (xyhw[0] == data->x_ply && xyhw[1] == data->y_ply)
		draw_player(data, xyhw);
	else if (xyhw[0] < 0 || xyhw[1] < 0 || xyhw[1] >= data->h_map
		|| xyhw[0] >= data->w_map)
		mpi(data, data->imgs.bg,
			xyhw[3] + ((xyhw[0] - data->x_ply) * data->size),
			xyhw[2] + ((xyhw[1] - data->y_ply) * data->size));
	else
		mpi(data, assets(data, xyhw[0], xyhw[1]),
			xyhw[3] + ((xyhw[0] - data->x_ply) * data->size),
			xyhw[2] + ((xyhw[1] - data->y_ply) * data->size));
}

void	pre_draw(t_data *data)
{
	int	xyhw[4];
	int	range;

	if (has_element(data->map, 'C'))
		range = 2;
	else
		range = 4;
	xyhw[2] = data->h_scr / 2;
	xyhw[3] = data->w_scr / 2;
	xyhw[0] = data->x_ply - range - 1;
	while (++xyhw[0] <= data->x_ply + range)
	{
		while (xyhw[0] < -1)
			xyhw[0]++;
		xyhw[1] = data->y_ply - range - 1;
		while (++xyhw[1] <= data->y_ply + range)
			draw(data, xyhw);
	}
}
