package com.blarg.gdx.tilemap3d.prefabs.json;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Base64Coder;
import com.badlogic.gdx.utils.Json;
import com.blarg.gdx.Strings;
import com.blarg.gdx.tilemap3d.json.TileDataSerializer;
import com.blarg.gdx.tilemap3d.prefabs.TilePrefab;

import java.nio.ByteBuffer;

public class TilePrefabLoader {
	public static TilePrefab load(String prefabFile) {
		return load(Gdx.files.internal(prefabFile));
	}

	public static TilePrefab load(FileHandle prefabFile) {
		if (prefabFile == null)
			throw new IllegalArgumentException();

		Json json = new Json();
		JsonTilePrefab jsonPrefab = json.fromJson(JsonTilePrefab.class, prefabFile);

		if (Strings.isNullOrEmpty(jsonPrefab.data))
			throw new RuntimeException("Invalid prefab: no tile data.");

		TilePrefab prefab = new TilePrefab(jsonPrefab.width, jsonPrefab.height, jsonPrefab.depth);

		byte[] dataBytes = Base64Coder.decode(jsonPrefab.data);
		ByteBuffer buffer = ByteBuffer.wrap(dataBytes);

		TileDataSerializer.deserialize(buffer, prefab);

		return prefab;
	}
}

@@ -1106,11 +1106,753 @@
 efab;%0A%09%7D
+%0A%0A%09public static void save(TilePrefab prefab, String outputFilename) %7B%0A%09%09if (prefab == null)%0A%09%09%09throw new IllegalArgumentException();%0A%0A%09%09JsonTilePrefab jsonPrefab = new JsonTilePrefab();%0A%09%09jsonPrefab.width = prefab.getWidth();%0A%09%09jsonPrefab.height = prefab.getHeight();%0A%09%09jsonPrefab.depth = prefab.getDepth();%0A%0A%09%09byte%5B%5D dataBytes = new byte%5Bprefab.getData().length * TileDataSerializer.TILE_SIZE_BYTES%5D;%0A%09%09ByteBuffer buffer = ByteBuffer.wrap(dataBytes);%0A%0A%09%09TileDataSerializer.serialize(prefab, buffer);%0A%09%09jsonPrefab.data = new String(Base64Coder.encode(dataBytes));%0A%0A%09%09Json json = new Json();%0A%09%09String output = json.prettyPrint(jsonPrefab);%0A%09%09FileHandle outputFile = Gdx.files.local(outputFilename);%0A%09%09outputFile.writeString(output, false);%0A%09%7D
 %0A%7D%0A

add TilePrefab saving