/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   asset.c                                            :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/01/06 14:23:00 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/19 13:32:14 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "solong.h"

static void	*ft_gen_asset(char *color, size_t case_size, t_data *data)
{
	t_square	square;
	char		*name;
	int			dimmension;
	void		*img;

	square.color = color;
	square.size = case_size;
	name = ft_xpm_gen_file(square);
	if (name == NULL)
		return (NULL);
	img = mlx_xpm_file_to_image(data->mlx,
			name, &dimmension, &dimmension);
	free(name);
	return (img);
}

static char	**ft_color_gen(void)
{
	size_t	i;
	char	**tab;

	tab = ft_calloc(NB_COLORS + 1, sizeof(char *));
	if (tab == NULL)
		return (NULL);
	i = 0;
	while (i < NB_COLORS)
	{
		tab[i] = ft_ultoa_base(((1 << 23) * i) / NB_COLORS, HEX);
		if (tab[i] == NULL)
		{
			ft_cancel(tab, i);
			return (NULL);
		}
		i++;
	}
	tab[i] = NULL;
	return (tab);
}

int	ft_gen_assets(t_data *data)
{
	char		**colors;
	size_t		i;

	colors = ft_color_gen();
	if (colors == NULL)
		return (1);
	i = 0;
	while (i < NB_COLORS)
	{
		data->assets[i] = ft_gen_asset(colors[i], CASE_SIZE, data);
		if (data->assets[i] == NULL)
		{
			ft_freer_tab_ultimate(1, colors);
			return (1);
		}
		data->assets[i + NB_COLORS] = ft_gen_asset(colors[i],
				(RENDER_DISTANCE * 2 + 1) * CASE_SIZE, data);
		if (data->assets[i + NB_COLORS] == NULL)
			ft_freer_tab_ultimate(1, colors);
		if (data->assets[i + NB_COLORS] == NULL)
			return (1);
		i++;
	}
	ft_freer_tab_ultimate(1, colors);
	return (0);
}
