/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parse_token.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: gbrochar <gbrochar@student.42.fr>          +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/12/23 17:33:33 by gbrochar          #+#    #+#             */
/*   Updated: 2024/04/25 16:33:25 by gbrochar         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "scop.h"

int					parse_append_data_d(t_buf_d *buffer, char *token)
{
	if (buffer->ptr == buffer->len)
	{
		buffer->data = (double *)realloc(
			buffer->data, sizeof(double) * (buffer->len + BUFFER_SIZE));
		buffer->len += BUFFER_SIZE;
	}
	buffer->data[buffer->ptr] = atof(token);
	buffer->ptr++;
	return (SUCCESS);
}

int					parse_append_data_ui(t_buf_ui *buffer, char *token)
{
	if (buffer->ptr == buffer->len)
	{
		buffer->data = (unsigned int *)realloc(
			buffer->data, sizeof(unsigned int) * (buffer->len + BUFFER_SIZE));
		buffer->len += BUFFER_SIZE;
	}
	buffer->data[buffer->ptr] = atoi(token) - 1;
	buffer->ptr++;
	return (SUCCESS);
}

int					parse_append_data_index(t_env *e, char *phrase) {
	char *token;
	size_t token_count = 0;
	int ret;

	while ((token = strtok_r(phrase, "/", &phrase))) {
		if (token_count == 0) {
			ret = parse_append_data_ui(&(e->object.vertices_indices), token);
		}
		else if (token_count == 1) {
			ret = parse_append_data_ui(&(e->object.uvs_indices), token);
		}
		else if (token_count == 2) {
			ret = parse_append_data_ui(&(e->object.normals_indices), token);
		}
		token_count++;
	}
	return ret;
}

int					parse_token(
	t_env *e,
	char *token,
	t_gl_buf_type gl_buf_type)
{
	int				ret;

	if (gl_buf_type == OTHER)
		ret = BREAK;
	if (gl_buf_type == VERTEX)
		ret = parse_append_data_d(&(e->object.vertices), token);
	if (gl_buf_type == UV)
		ret = parse_append_data_d(&(e->object.uvs), token);
	if (gl_buf_type == NORMAL)
		ret = parse_append_data_d(&(e->object.normals), token);
	if (gl_buf_type == INDEX)
		ret = parse_append_data_index(e, token);
	return (ret);
}

