#include "load_obj.hh"

#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
#include <QFile>
#include <QDebug>


QVector<GLfloat> load_obj(const char *path, int flags) {
	QFile obj_file(path);
	obj_file.open(QIODevice::ReadOnly | QIODevice::Text);
	std::string obj = obj_file.readAll().toStdString();
	tinyobj::ObjReaderConfig cfg;
	cfg.triangulate = true;
	cfg.vertex_color = false;
	tinyobj::ObjReader reader;
	if (!reader.ParseFromString(obj, "", cfg)) {
		if (!reader.Error().empty()) {
			qWarning() << "Erreur lors de la lecture de du modèle";
		}
		exit(1);
	}
	// if (!reader.Warning().empty()) {
	// 	qWarning() << "TinyObjReader: " << reader.Warning();
	// }
	auto& attrib = reader.GetAttrib();
	auto& shapes = reader.GetShapes();

	QVector<GLfloat> verts;

	for (size_t s = 0; s < shapes.size(); s++) {
		// Loop over faces(polygon)
		size_t index_offset = 0;
		for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
			size_t fv = shapes[s].mesh.num_face_vertices[f];

			// Loop over vertices in the face.
			for (size_t v = 0; v < fv; v++) {
				tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
				tinyobj::real_t vx = attrib.vertices[3*idx.vertex_index+0];
				tinyobj::real_t vy = attrib.vertices[3*idx.vertex_index+1];
				tinyobj::real_t vz = attrib.vertices[3*idx.vertex_index+2];
				verts.append(vx);
				verts.append(vy);
				verts.append(vz);

				if (flags & LOAD_OBJ_NORMALS) {
					tinyobj::real_t nx = attrib.normals[3*idx.normal_index+0];
					tinyobj::real_t ny = attrib.normals[3*idx.normal_index+1];
					tinyobj::real_t nz = attrib.normals[3*idx.normal_index+2];
					verts.append(nx);
					verts.append(ny);
					verts.append(nz);
				}

				if (flags & LOAD_OBJ_UVS) {
					tinyobj::real_t ts = attrib.texcoords[2*idx.texcoord_index+0];
					tinyobj::real_t tt = attrib.texcoords[2*idx.texcoord_index+1];
					verts.append(ts);
					verts.append(tt);
				}
				// qDebug() << "vert" << vx << vy << vz << "tex" << ts << tt;
			}
			index_offset += fv;
		}
	}
	return verts;
}
