/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   render.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: erey-bet <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/12/29 18:06:42 by erey-bet          #+#    #+#             */
/*   Updated: 2023/01/04 16:47:26 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_player, 2) + pow(y - data->y_player, 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]);
	else if (c == 'e')
		return (data->imgs.ene);
	return (data->imgs.bg);
}

void	draw(t_data *data)
{
	int	x;
	int	y;
	int	range;

	if (has_element(data->map, 'C'))
		range = 2;
	else
	{
		if (data->x_ene == -1)
			data->x_ene = data->x_player;
		range = 4;
	}
	x = data->x_player - range;
	while (x <= data->x_player + range)
	{
		while (x < -1)
			x++;
		y = data->y_player - range;
		while (y <= data->y_player + range)
		{
			while (y < -1)
				y++;
			if (x == data->x_player && y == data->y_player)
				if (has_element(data->map, 'C'))
					mlx_put_image_to_window(data->mlx, data->mlx_win, data->imgs.ply[(x + y) % 4], data->w_screen / 2, data->h_screen / 2);
				else
					mlx_put_image_to_window(data->mlx, data->mlx_win, data->imgs.ply[((x + y) % 4) + 4], data->w_screen / 2, data->h_screen / 2);
			else if (y < 0 || x < 0 || y >= data->h_map || x >= data->w_map) 
				mlx_put_image_to_window(data->mlx, data->mlx_win, data->imgs.bg, (data->w_screen / 2) + ((x - data->x_player) * data->size), (data->h_screen / 2) + ((y - data->y_player) * data->size));
			else 
				mlx_put_image_to_window(data->mlx, data->mlx_win, assets(data, x, y), (data->w_screen / 2) + ((x - data->x_player) * data->size), (data->h_screen / 2) + ((y - data->y_player) * data->size));
			y++;
		}
		x++;
	}
}
