/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   sl_screen.c                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: bchanot <bchanot@students.42.fr>           +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2016/11/02 19:41:12 by bchanot           #+#    #+#             */
/*   Updated: 2016/11/17 02:41:24 by bchanot          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_select.h"
#include <term.h>
#include <sys/ioctl.h>

static int	sl_take_max(t_inf *inf)
{
	int	len;
	int	cpt;

	len = ft_strlen(inf->args[0]);
	cpt = 1;
	while (inf->args[cpt])
	{
		if (len < (int)ft_strlen(inf->args[cpt]))
			len = ft_strlen(inf->args[cpt]);
		cpt++;
	}
	return (len);
}

static void	sl_turn_on_off(t_inf *inf, int disp, int bool)
{
	if (bool)
	{
		if (inf->selected[disp])
			ft_putstr_fd(tgetstr("so", NULL), 0);
		if (disp == inf->cur)
			ft_putstr_fd(tgetstr("us", NULL), 0);
		return ;
	}
	if (inf->selected[disp])
		ft_putstr_fd(tgetstr("se", NULL), 0);
	if (disp == inf->cur)
		ft_putstr_fd(tgetstr("ue", NULL), 0);
}

void		sl_display_screen(t_inf *inf)
{
	int				cpt;
	int				disp;
	int				cpt2;
	int				len;
	struct winsize	w;

	ioctl(0, TIOCGWINSZ, &w);
	ft_putstr_fd(tgetstr("cl", NULL), 0);
	if (((inf->nb / (w.ws_row - 1)) + (inf->nb % (w.ws_row - 1) ? 1 : 0)) *
		(sl_take_max(inf) + 1) >= w.ws_col || (cpt = -1) == 0)
		return (ft_putstr_fd("/!\\\n", 0));
	while (++cpt < inf->nb && cpt < w.ws_row - 1)
	{
		cpt2 = -1;
		while (((disp = ((w.ws_row - 1) * ++cpt2) + cpt)) < inf->nb)
		{
			sl_turn_on_off(inf, disp, 1);
			ft_putstr_fd(inf->args[disp], 0);
			sl_turn_on_off(inf, disp, 0);
			len = ft_strlen(inf->args[disp]);
			while (++len <= sl_take_max(inf) + 1)
				ft_putchar_fd(' ', 0);
		}
		ft_putchar_fd('\n', 0);
	}
}
