/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   sl_take_inf.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: bchanot <bchanot@students.42.fr>           +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2016/11/02 19:06:15 by bchanot           #+#    #+#             */
/*   Updated: 2016/11/16 22:25:33 by bchanot          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_select.h"
#include <term.h>
#include <stdlib.h>

t_inf	*sl_set_inf(t_inf *inf)
{
	static t_inf *env = NULL;

	if (inf)
		env = inf;
	return (env);
}

void	sl_exit(char *str, t_inf *inf, int bool)
{
	if (bool)
	{
		inf->term.c_lflag |= (ICANON | ECHO);
		tcsetattr(0, 0, &inf->term);
	}
	ft_memdel2((void ***)&inf->args);
	ft_memdel((void **)&inf->selected);
	if (str)
		ft_putstr_fd(str, 2);
	exit(0);
}

void	sl_init_term(t_inf *inf)
{
	char			*name;

	if (!(name = getenv("TERM")))
		sl_exit("Failed getting TERM environnement\n", inf, 0);
	if (tgetent(NULL, name) <= 0)
		sl_exit("Failed getting TERM environnement\n", inf, 0);
	tcgetattr(0, &inf->term);
	inf->term.c_lflag &= ~(ICANON);
	inf->term.c_lflag &= ~(ECHO);
	inf->term.c_cc[VMIN] = 1;
	inf->term.c_cc[VTIME] = 0;
	if (tcsetattr(0, TCSADRAIN, &inf->term) == -1)
		sl_exit("Failed to set termios\n", inf, 1);
	ft_putstr_fd(tgetstr("ti", NULL), 0);
	ft_putstr_fd(tgetstr("vi", NULL), 0);
}

void	sl_init_inf(int ac, char **av, t_inf *inf)
{
	int	cpt;
	int	cpt2;

	cpt = 0;
	cpt2 = 0;
	inf->args = (char **)ft_memalloc(sizeof(char *) * (ac));
	inf->args[ac - 1] = 0;
	while (++cpt < ac)
	{
		inf->args[cpt2] = ft_strdup(av[cpt]);
		cpt2++;
	}
	inf->nb = ac - 1;
	inf->selected = (int *)ft_memalloc(sizeof(int) * (ac - 1));
	ft_bzero(inf->selected, (sizeof(int) * (ac - 1)));
	inf->cur = 0;
	sl_init_term(inf);
}
