#include "fileManager.h"
#include <SDL2/SDL.h>
#include <fstream>

#pragma pack(push,1)

struct DATA_Header {
	char magic[4];
	Uint32 num_files;
	Uint32 index_offset;
};

struct DATA_Info {
	Uint32	offset;
	Uint32	length;
	char	name[13];
};

struct DATA_Index {
	DATA_Info*	file_info;
};

struct DATA_File {
	DATA_Header	header;
	DATA_Index	index;
};

#pragma pack(pop)

static const char *resourceFileName = "data.jrf";
static DATA_File *data_file = NULL;

void file_setResourceFile(const char *p_resourceFileName) {
	resourceFileName = p_resourceFileName;
}

static void getDataFile() {
	std::ifstream fd( resourceFileName, std::ios::in | std::ios::binary );

	if( fd.fail() ) {
		perror("No s'ha pogut obrir l'arxiu de recursos");
		exit(1);
	}
	
	data_file = (DATA_File*)malloc( sizeof( DATA_File ) );

	fd.read( (char*)&data_file->header, sizeof( DATA_Header ) );

	fd.seekg( data_file->header.index_offset );

	data_file->index.file_info = (DATA_Info*)malloc( data_file->header.num_files * sizeof( DATA_Info ) );

	fd.read( (char*)data_file->index.file_info, data_file->header.num_files * sizeof( DATA_Info ) );

	fd.close();
}

const char *file_setBufferFromResource(const char *resourcename, int& filesize) {

	if( data_file == NULL ) {
		getDataFile();
	}

	bool found = false;
	int count = 0;
	while( !found && count < data_file->header.num_files ) {
		found = ( strcmp( resourcename, data_file->index.file_info[count].name ) == 0 );
		if( !found ) count++;
	}

	if( !found ) {
		perror("El recurs no s'ha trobat en l'arxiu de recursos");
		exit(1);
	}

	filesize = data_file->index.file_info[count].length;

	std::ifstream fd( resourceFileName, std::ios::in | std::ios::binary );

	if( fd.fail() ) {
		perror("No s'ha pogut obrir l'arxiu de recursos");
		exit(1);
	}

	fd.seekg( data_file->index.file_info[count].offset );
	
	char* buffer = (char*)malloc( filesize );
	fd.read( buffer, filesize );

	fd.close();

	return buffer;
}

void file_quit() {
	if( data_file != NULL ) {
		free( data_file->index.file_info );
		free( data_file );
	}
}
