/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   sl_core.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: bchanot <bchanot@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2018/09/24 00:03:51 by bchanot           #+#    #+#             */
/*   Updated: 2018/10/14 04:29:32 by bchanot          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_ssl.h"

void		sl_choose_hash(t_inf *inf)
{
	static void	(*func[NB_HASH])(const char *str) = {HASH_FUNCTIONS};
	const char	*(hash[NB_HASH + 1]) = {HASH_TAB, NULL};
	size_t		i;

	i = -1;
	while (hash[++i])
	{
		if (!ft_strcmp(inf->hash_tag, hash[i]))
		{
			inf->func = func[i];
			break ;
		}
	}
}

static void	sl_print_and_launch(t_inf *inf, t_files *file, size_t i)
{
	if (!file->name)
	{
		if (ft_check_opts(inf->opts, "p") && i == 0)
			ft_printf(1, "%s%c", file->string, file->string[ft_strlen(
						file->string) - 1] == '\n' ? 0 : '\n');
		else if (file->s_opt && !ft_check_opts(inf->opts, "r") &&
				!ft_check_opts(inf->opts, "q"))
			ft_printf(1, "%s (\"%s\")= ", inf->hash_tag, file->string);
	}
	else if (!ft_check_opts(inf->opts, "r") && !ft_check_opts(inf->opts, "q"))
		ft_printf(1, "%s (%s)= ", ft_str_upper(inf->hash_tag), file->name);
	inf->func(file->string);
	if (!ft_check_opts(inf->opts, "q") && ft_check_opts(inf->opts, "r"))
	{
		if (file->name)
			ft_printf(1, " %s", file->name);
		else if (file->s_opt)
			ft_printf(1, " \"%s\"", file->string);
	}
	ft_putchar('\n');
}

void		sl_prepare_launch(t_inf *inf)
{
	t_files	*tmp;
	size_t	i;

	tmp = inf->files;
	i = 0;
	while (tmp)
	{
		if (!tmp->string)
			ft_printf(2, "ft_ssl: %s: %s: No such file or directory\n",
					ft_str_lower(inf->hash_tag), tmp->name);
		else
			sl_print_and_launch(inf, tmp, i++);
		tmp = tmp->next;
	}
}
