/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: bchanot <bchanot@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2018/09/20 23:08:43 by bchanot           #+#    #+#             */
/*   Updated: 2018/10/26 10:54:30 by bchanot          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_ssl.h"

static void	sl_free_inf(t_inf *inf)
{
	t_files	*tmp;

	while (inf->files)
	{
		tmp = inf->files->next;
		ft_memdel((void **)&inf->files->string);
		ft_memdel((void **)&inf->files->name);
		ft_memdel((void **)&inf->files);
		inf->files = tmp;
		tmp = NULL;
	}
	ft_memdel2((void ***)&inf->opts);
}

static void	sl_error(int state, char *str)
{
	const char	*(hash[NB_HASH + 1]) = {HASH_TAB, NULL};
	size_t		i;

	i = 0;
	if (state == 1)
		ft_printf(2, "Usage: ft_ssl command [command opts] [command args]");
	else if (state == 2)
	{
		ft_printf(2, "ft_ssl: Error: '%s' is an invalid command.\n\n\
Standard commands:\n\nMessage Digest commands:\n", str);
		while (hash[i])
		{
			ft_printf(2, "%s\n", hash[i]);
			i++;
		}
		ft_printf(2, "\nCipher commands:\n");
	}
}

static char	**sl_get_args(t_bool in, char **av)
{
	char	*line;
	char	*tmp;
	char	**args;

	if (in)
	{
		line = NULL;
		ft_printf(1, "ft_SSL> ");
		get_next_line(0, &line);
		if (!line)
			return (NULL);
		tmp = ft_strtrim(line);
		ft_memdel((void **)&line);
		args = ft_strsplit(tmp, ' ');
		ft_memdel((void **)&tmp);
		return (args);
	}
	return (av + 1);
}

static int	sl_start(t_bool in, char **args, int ac, t_int8 *ret)
{
	t_inf	inf;

	ft_bzero(&inf, sizeof(t_inf));
	*ret = sl_get_inf(&inf, in ? (int)ft_tablen(args) : ac - 1, args);
	if (!(*ret))
	{
		sl_choose_hash(&inf);
		sl_prepare_launch(&inf);
	}
	else
		sl_error(*ret, in ? args[0] : NULL);
	sl_free_inf(&inf);
	return (in ? 1 : 0);
}

int			main(int ac, char **av)
{
	t_int8	ret;
	t_bool	in;
	char	**args;

	in = ac == 1 ? true : false;
	while (true)
	{
		if (!(args = sl_get_args(in, av)))
			break ;
		if (!sl_start(in, args, ac, &ret))
			break ;
		if (in)
			ft_memdel2((void ***)&args);
	}
	return (ret);
}
