import aliases;
import util;
import std.stdio;
import std.file;
import std.string;
import std.path;
import std.uni;
import std.conv;
import std.array;

void
main()
{
	CreateAssetLookups();
}

void
CreateAssetLookups()
{
	try
	{
		mkdir("src/generated");
	}
	catch(Exception e) {}

	string[] dirs;
	string[][string] file_names;
	string[][string] base_names;
	u64[][string] file_hashes;

	foreach(string dir; dirEntries("assets", SpanMode.shallow))
	{
		dirs ~= baseName(dir);
	}

	foreach(dir; dirs)
	{
		string[] files;
		string[] names;
		foreach(string file; dirEntries("assets/" ~ dir, SpanMode.shallow))
		{
			files ~= dir ~ "/" ~ baseName(file);
			names ~= dir ~ "/" ~ baseName(stripExtension(file));
		}

		file_names[dir] = files;
		base_names[dir] = names;
	}

	foreach(dir, names; base_names)
	{
		u64[] hashes;
		foreach(name; names)
		{
			hashes ~= Hash(name);
		}

		file_hashes[dir] = hashes;
	}

	auto f = File("src/generated/assets_codegen.d", "w");
	scope(exit) f.close();

	string asset_str = "import aliases;\n\n";

	asset_str ~= "enum AssetType : u32\n{\n\tNone,\n";
	foreach(i, dir; dirs)
	{
		auto graphemes = dir.byGrapheme.array;
		string upper = [graphemes[0]].byCodePoint.text.toUpper;
		graphemes[0] = upper.decodeGrapheme;

		string asset_type = graphemes.byCodePoint.text.stripRight("s");
		asset_str ~= format("\t%s,\n", asset_type);
	}
	asset_str ~= "}\n\nalias AT = AssetType;\n\n";

	foreach(dir; dirs)
	{
		string asset_type = stripRight(dir, "s").toUpper();

		asset_str ~= format("static immutable string[] %s_FILES = [\n", asset_type);
		foreach(file; file_names[dir])
		{
			asset_str ~= format("\t\"%s\",\n", file);
		}
		asset_str ~= "];\n\n";


		asset_str ~= format("static immutable string[] %s_NAMES = [\n", asset_type);
		foreach(name; base_names[dir])
		{
			asset_str ~= format("\t\"%s\",\n", name);
		}
		asset_str ~= "];\n\n";

		asset_str ~= format("static immutable u64[] %s_HASHES = [\n", asset_type);
		foreach(hash; file_hashes[dir])
		{
			asset_str ~= format("\t%d,\n", hash);	
		}
		asset_str ~= "];\n\n";

	}

	f.write(asset_str);
}
