/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   sl_get_inf.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: bchanot <bchanot@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2018/09/24 00:05:18 by bchanot           #+#    #+#             */
/*   Updated: 2018/10/14 04:07:11 by bchanot          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_ssl.h"
#include <fcntl.h>
#include <unistd.h>

static t_files	*sl_get_infos(char *name, t_bool chk)
{
	t_files	*files;
	int		fd;

	files = (t_files *)ft_memalloc(sizeof(t_files));
	files->s_opt = chk;
	if (chk)
	{
		files->name = NULL;
		files->string = ft_strdup(name);
		return (files);
	}
	fd = !name ? 0 : open(name, O_RDONLY);
	if (fd > -1)
		files->string = ft_get_file_content(fd);
	if (fd > 0)
		close(fd);
	if (!files->string && fd == 0)
		files->string = ft_strdup("");
	files->name = ft_strdup(name);
	return (files);
}

static void		sl_add_file(t_inf *inf, char *name, t_bool chk)
{
	t_files	*tmp;

	if (!inf->files)
	{
		inf->files = sl_get_infos(name, chk);
		inf->files->next = NULL;
	}
	else
	{
		tmp = inf->files;
		while (tmp->next)
			tmp = tmp->next;
		tmp->next = sl_get_infos(name, chk);
		tmp->next->next = NULL;
	}
}

static int		sl_check_command(t_inf *inf, char *cmd)
{
	const char	*(hash[NB_HASH + 1]) = {HASH_TAB, NULL};
	size_t		i;

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

int				sl_get_inf(t_inf *inf, int ac, char **av)
{
	size_t	i;
	char	**args;

	if (!ac)
		return (1);
	if (sl_check_command(inf, *av))
		return (2);
	av++;
	inf->opts = ft_take_opts_begin(ac - 1, av);
	args = ft_take_args_begin(ac - 1, av);
	if (!args || ft_check_opts(inf->opts, "p"))
		sl_add_file(inf, NULL, false);
	i = 0;
	if (args && args[i] && ft_check_opts(inf->opts, "s"))
	{
		sl_add_file(inf, args[i], true);
		i++;
	}
	while (args && args[i])
	{
		sl_add_file(inf, args[i], false);
		i++;
	}
	ft_memdel2((void ***)&args);
	return (0);
}
