/* ************************************************************************** */
/*                                                          LE - /            */
/*                                                              /             */
/*   ft_history.c                                     .::    .:/ .      .::   */
/*                                                 +:+:+   +:    +:  +:+:+    */
/*   By: rbousset <marvin@le-101.fr>                +:+   +:    +:    +:+     */
/*                                                 #+#   #+    #+    #+#      */
/*   Created: 2019/10/30 20:36:05 by rbousset     #+#   ##    ##    #+#       */
/*   Updated: 2019/10/30 20:36:07 by rbousset    ###    #+. /#+    ###.fr     */
/*                                                         /                  */
/*                                                        /                   */
/* ************************************************************************** */

#include <libft.h>
#include <minishell.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

// static size_t
// ft_count_lines(int fd)
// {
// 	char c;
// 	size_t lines;
// 
// 	lines = 0;
// 	while (read(fd, &c, 1) > 0)
// 		if (c == '\n')
// 			lines++;
// 	return (lines);
// }
// 
// static size_t
// ft_last_line_len(int fd, size_t lines_max)
// {
// 	char c;
// 	size_t len;
// 	size_t lines;
// 
// 	len = 0;
// 	lines = 0;
// 	while (read(fd, &c, 1) > 0)
// 	{
// 		if (c == '\n')
// 			lines++;
// 		if (lines == lines_max - 1)
// 			break ;
// 	}
// 	while (read(fd, &c, 1) > 0)
// 		len++;
// 	return (len);
// }
// 
char
*ft_get_last_line(void)
{
	char	*line;
	int		ret;
	int		fd;

	if ((fd = open("joe-sh_history", O_CREAT | O_RDWR, 0644)) == -1)
		return (NULL);
	while ((ret = get_next_line(fd, &line)) > 0)
	{
		ft_putendl(line);
		free(line);
	}
	close(fd);
	return (line);
}

/*
** Prints user-given line into
** joe-sh_hisotry
*/

int
ft_history(char *arg)
{
	char *buff;
	int fd;
	int ret;
	// struct stat info;

	if (!*arg)
		return (0);
	if ((fd = open("joe-sh_history", O_CREAT | O_RDWR, 0644)) == -1)
		return (1);
	// fstat(fd, &info);
	// if (!(buff = (char*)malloc(info.st_size * sizeof(char))))
	// 	return (0);
	// ret = read(fd, buff, info.st_size);
	ret = get_next_line(fd, &buff);
	free(buff);
	while (ret)
	{
		ret = get_next_line(fd, &buff);
		if (ret == 0)
			break ;
		free(buff);
	}
	ft_putendl_fd(arg, fd);
	free(buff);
	close(fd);
	return (0);
}