#include "fdf.h"

static int	tab_to_color(t_color **color, char **tab)
{
	int 	red;
	int		green;
	int		blue;

	red = ft_atoi(tab[0]);
	green = ft_atoi(tab[1]);
	blue = ft_atoi(tab[2]);
	if (red > 255 || red < 0 ||
		green > 255 || green < 0 ||
		blue > 255 || blue < 0)
		return (0);
	(*color)->red = red;
	(*color)->green = green;
	(*color)->blue = blue;
	return (1);
}

static void	wrong_heatmap(t_color **low, t_color **high)
{
	ft_putstr("wrong heatmap! Type \"fdf --help\" for heatmap example\n");
	free(*low);
	free(*high);
	*low = NULL;
	*high = NULL;
}

static void	parse_heatmap(char *hm, t_color **low, t_color **high)
{
	char 	**hm_tab;
	char 	**low_tab;
	char 	**high_tab;

	*low = malloc(sizeof(t_color));
	*high = malloc(sizeof(t_color));
	hm_tab = ft_strsplit(hm, '-');
	if ((tab_length(hm_tab) != 2))
	{
		wrong_heatmap(low, high);
		return ;
	}
	low_tab = ft_strsplit(hm_tab[0], ',');
	high_tab = ft_strsplit(hm_tab[1], ',');
	if (tab_length(low_tab) != 3 || tab_length(high_tab) != 3)
	{
		wrong_heatmap(low, high);
		return ;
	}
	if (!tab_to_color(low, low_tab) || !tab_to_color(high, high_tab))
	{
		wrong_heatmap(low, high);
		return ;
	}
}

void	parse_input(int ac, char **av, t_FDF **FDF)
{
	t_color *low;
	t_color	*high;

	low = NULL;
	high = NULL;
	if ((ac < 2 || ac > 4) || (ac == 2 && ft_strstr(av[1], "--help")))
	{
		print_help();
		quit(*FDF);
	}
	else if (ac == 2)
		*FDF = FDF_init(av[1], low, high);
	else if (ac == 4 && ft_strstr(av[1], "--heatmap"))
	{
		parse_heatmap(av[2], &low, &high);
		*FDF = FDF_init(av[3], low, high);
	}
	else
	{
		print_help();
		quit(*FDF);
	}
}