#pragma once
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define M3DMAGIC "M3DM"
const uint16_t VER_MAGIC=2;

#pragma pack(push, 1)
struct M3DM_Header
{
	char signature[4];
	uint16_t version;
	uint8_t data_offset;
	uint8_t model_name_length;
	uint16_t texture_path_length;
	uint32_t vertex_data_size;
	uint32_t index_data_size;
	uint8_t primitive_type;
}m3dm_header;
struct M3DM_ModelName_Block
{
	char *name;
} m3dm_model_name;
struct M3DM_TexturePath_Block
{
	char *texture_path;
}m3dm_texture_path;
struct M3DM_VertexData_Block
{
	float x;
	float y;
	float z;
	float u;
	float v;
	float nx;
	float ny;
	float nz;
} *m3dm_vertex_data;
struct M3DM_IndexData_Block
{
	uint32_t index;
} *m3dm_index_data;
#pragma pack(pop)

bool m3dm_write_file(char *fname)
{
	memcpy(m3dm_header.signature, M3DMAGIC, 4);
	m3dm_header.version = VER_MAGIC;
	m3dm_header.data_offset = sizeof(m3dm_header);

	int fdesc = creat(fname, 0666);
	if(fdesc<=0)
	{
		std::cerr<<"can't create output file:"<<fname<<std::endl;
		return false;
	}
	
	write(fdesc, &m3dm_header, sizeof(m3dm_header));
	write(fdesc, m3dm_model_name.name, m3dm_header.model_name_length);
	write(fdesc, m3dm_texture_path.texture_path, m3dm_header.texture_path_length);
	write(fdesc, m3dm_vertex_data, m3dm_header.vertex_data_size);
	write(fdesc, m3dm_index_data, m3dm_header.index_data_size);
	close(fdesc);
	return true;
}
