/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   check_rgb.c                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <pblagoje@student.42.fr>          +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/04/15 16:11:24 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 16:46:11 by pblagoje         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static int	check_colors(char **str)
{
	int	i;
	int	num;

	i = 0;
	num = 0;
	while (str && str[i])
	{
		num = ft_atoi(str[i]);
		if (num < 0 || num > 255)
			return (EXIT_FAILURE);
		i++;
	}
	return (EXIT_SUCCESS);
}

static int	ft_strlen_2d(char **str)
{
	int	i;

	i = 0;
	while (str && str[i])
		i++;
	return (i);
}

static void	set_rgb(int *plan, char **rgb)
{
	int	r;
	int	g;
	int	b;

	r = ft_atoi(rgb[0]);
	g = ft_atoi(rgb[1]);
	b = ft_atoi(rgb[2]);
	*plan = 0 << 24 | r << 16 | g << 8 | b;
}

int	check_rgb(t_txt *txt, char *elem, char identifier)
{
	char	**rgb;

	rgb = ft_split(elem, ',');
	mb_add_2d((void **)rgb, ft_strlen_2d(rgb));
	if (!rgb || ft_strlen_2d(rgb) != 3 || elem[ft_strlen(elem) - 1] == ',')
		mb_exit("Error\nInvalid RGB code.\n", EXIT_FAILURE);
	if ((identifier != 'F' && identifier != 'C') || check_colors(rgb))
		mb_exit("Error\nInvalid RGB code.\n", EXIT_FAILURE);
	if (identifier == 'F')
		set_rgb(&txt->rgb_floor, rgb);
	else
		set_rgb(&txt->rgb_ceiling, rgb);
	mb_free_2d((void **)rgb, ft_strlen_2d(rgb));
	return (EXIT_SUCCESS);
}
