/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parsing.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: axdubois <axdubois@student.42.fr>          +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/07/31 23:10:14 by axdubois          #+#    #+#             */
/*   Updated: 2023/08/02 19:39:26 by axdubois         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../../includes/utils-h/utils.h"
#include "../../includes/utils-h/fst_line.h"

int	ft_get_nobj(int file, char o)
{
	int		count;
	char	*buf;

	count = 0;
	buf = malloc(1);
	while (read(file, &buf, 1) > 0)
	{
		read(file, &buf, 1);
		if (*buf == o)
			count++;
	}
	free(buf);
	close(file);
	return (count);
}

int	ft_get_y(int file, int obj_c, char o)
{
	int		count_obj;
	int		y_obj;
	char	*buf;

	y_obj = 0;
	count_obj = 0;
	buf = malloc(1);
	while (*buf)
	{
		read(file, &buf, 1);
		if (*buf == '\n')
			y_obj++;
		if (*buf == o)
		{
			count_obj++;
			if (obj_c == count_obj)
				return (y_obj);
		}
	}
	free(buf);
	return(0);
}

int	ft_get_x(int file, int obj_c, char o)
{
	int		count_obj;
	int		x_obj;
	char	*buf;

	x_obj = 0;
	count_obj = 0;
	buf = malloc(1);
	while (*buf)
	{
		read(file, &buf, 1);
		if (*buf == '\n')
			x_obj = 0;
		if (*buf == o)
		{
			count_obj++;
			if (obj_c == count_obj)
				return (x_obj);
		}
		x_obj++;
	}
	free(buf);
	return (0);
}

t_coords	*ft_get_list_obj(int file, char o)
{
	t_coords	*list_obj;
	int			i;
	int			*buf;
	int			obj_c;

	list_obj = malloc(sizeof(t_coords) * ft_get_nobj(file, o));
	if (list_obj == NULL)
		return (NULL);
	i = 0;
	obj_c = 0;
	buf = malloc(1);
	while (i < ft_get_nobj(file, o))
	{
		read(file, &buf, 1);
		if (*buf == o)
		{
			obj_c++;
			list_obj[i].x = ft_get_x(file, obj_c, o);
			list_obj[i].y =	ft_get_y(file, obj_c, o);
		}
		i++;
	}
	list_obj[i].x = ft_len_line(file, 1);
	list_obj[i].y = ft_len_colum(file);
	i++;
	list_obj[i].x = -1;
	list_obj[i].y = -1;
	free(buf);
	return (list_obj);
}