#include "generator.h"

#include "piiostream.h"
#include "piresourcesstorage.h"


PIString initName(const PIString & n) {
	return PIFile::fileInfo(n).baseName().replaceAll(".", "_").replaceAll("/", "_").replaceAll(":", "_").replaceAll("-", "_");
}


bool generate(const PIString & init_name, PIFile & file, const PIVector<ParserSection> & files) {
	if (!file.isOpened()) return false;
	PIString fcname   = initName(file.path());
	PIString icname   = "_PIRC_" + fcname + "_Initializer_";
	PIString dataname = "_pirc_" + fcname + "_data_";
	PIString descname = "_pirc_" + fcname + "_desc_";
	PIString funcname = "_pirc_" + init_name + "_init_";
	PIVector<PIResourcesStorage::__RCEntry> fv;
	for (const auto & s: files) {
		for (const auto & p: s.files) {
			PIFile f;
			if (!f.open(p.path, PIIODevice::ReadOnly)) continue;
			// piCout << "gen" << p.name << p.alias << p.path;
			fv << PIResourcesStorage::__RCEntry(s.name, p.name, p.alias, p.path);
		}
	}
	if (fv.isEmpty()) return false;
	PIIOTextStream ts(&file);
	ts << "#include \"piresourcesstorage.h\"\n\nstatic const uchar " << dataname << "[] = {\n";
	bool first   = true;
	int rcnt     = -1;
	llong curoff = 0, curfile = 0;
	for (auto & e: fv) {
		e.offset = curoff;
		PIFile f;
		f.open(e.file, PIIODevice::ReadOnly);
		PIByteArray readed;
		curfile = 0;
		while (!f.isEnd()) {
			readed = f.read(4096);
			curfile += readed.size_s();
			for (int i = 0; i < readed.size_s(); ++i) {
				if (!first) ts << ',';
				first = false;
				if (++rcnt >= 32) {
					ts << '\n';
					rcnt = 0;
				}
				ts << int(readed[i]);
			}
		}
		e.size = curfile;
		curoff += curfile;
	}
	ts << "\n};\n";
	PIByteArray dba;
	dba << fv;
	ts << "\nstatic const uchar " << descname << "[] = {\n";
	first = true;
	rcnt  = -1;
	for (int i = 0; i < dba.size_s(); ++i) {
		if (!first) ts << ',';
		first = false;
		if (++rcnt >= 32) {
			ts << '\n';
			rcnt = 0;
		}
		ts << int(dba[i]);
	}
	ts << "\n};\n";

	ts << "\nvoid " << funcname << "() {\n";
	ts << "\tPIResourcesStorage::instance()->registerSection(" << dataname << ", " << descname << ", sizeof(" << descname << "));\n";
	ts << "}\n";

	ts << "\nclass " << icname << " {\n";
	ts << "public:\n\t" << icname << "() {\n";
	ts << "\t\t" << funcname << "();\n";
	ts << "\t}\n";
	ts << "} _pirc_" << fcname << "_initializer_;\n";
	return true;
}
