#include "resource.h"

#include "constants.h"
#include "errordialog.h"

#include "microtar.h"

namespace kek::Resource {

static mtar_t resources;

int init() {
	int r = mtar_open(&resources, "resources.tar", "r");
	if(r != MTAR_ESUCCESS) {
		ErrorDialog::showError("Failed to open resources.tar: " + std::string(mtar_strerror(r)));
		return KEK_ERROR;
	}

	return KEK_SUCCESS;
}

void destroy() {
	mtar_close(&resources);
}

/*MemoryBuffer *loadResource(std::string path) {
	std::ifstream in = std::ifstream(path, std::ios::binary);
	if(!in.good()) return nullptr;
	in.ignore(std::numeric_limits<std::streamsize>::max());
	std::streamsize size = in.gcount();
	in.clear();
	in.seekg(0, std::ios_base::beg);
	char *data = (char *) malloc(size);
	in.read(data, size);
	return new MemoryBuffer(data, size);
}*/

MemoryBuffer *loadResource(std::string path) {
	mtar_header_t h;
	int r = mtar_find(&resources, path.c_str(), &h);
	if(r != MTAR_ESUCCESS) {
		if(r == MTAR_ENOTFOUND) std::cerr << "Failed to find resource '" << path << "': " << mtar_strerror(r) << std::endl;
		return nullptr;
	}

	void *buf = malloc(h.size);
	r = mtar_read_data(&resources, buf, h.size);
	if(r != MTAR_ESUCCESS) {
		std::cerr << "Failed to read resource '" << path << "': " << mtar_strerror(r) << std::endl;
		return nullptr;
	}

	return new MemoryBuffer((char *) buf, h.size);
}

}
