package openmods.utils.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.UUID;

import openmods.utils.ByteUtils;

import com.google.common.base.Strings;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;

public class GameProfileSerializer implements IStreamSerializer<GameProfile> {
	public static final IStreamSerializer<GameProfile> INSTANCE = new GameProfileSerializer();

	@Override
	public void writeToStream(GameProfile o, DataOutput output) throws IOException {
		write(o, output);
	}

	@Override
	public GameProfile readFromStream(DataInput input) throws IOException {
		return read(input);
	}

	public static void write(GameProfile o, DataOutput output) throws IOException {
		final UUID uuid = o.getId();
		output.writeUTF(uuid == null? "" : uuid.toString());
		output.writeUTF(Strings.nullToEmpty(o.getName()));
		final PropertyMap properties = o.getProperties();
		ByteUtils.writeVLI(output, properties.size());
		for (Property p : properties.values()) {
			output.writeUTF(p.getName());
			output.writeUTF(p.getValue());
			output.writeUTF(p.getSignature());
		}
	}

	public static GameProfile read(DataInput input) throws IOException {
		final String uuidStr = input.readUTF();
		UUID uuid = UUID.fromString(uuidStr);
		final String name = input.readUTF();
		GameProfile result = new GameProfile(uuid, name);
		int propertyCount = ByteUtils.readVLI(input);

		final PropertyMap properties = result.getProperties();
		for (int i = 0; i < propertyCount; ++i) {
			String key = input.readUTF();
			String value = input.readUTF();
			String signature = input.readUTF();
			properties.put(key, new Property(key, value, signature));
		}

		return result;
	}
}

@@ -1162,24 +1162,131 @@
 etValue());%0A
+%0A%09%09%09final String signature = p.getSignature();%0A%09%09%09if (signature != null) %7B%0A%09%09%09%09output.writeBoolean(true);%0A%09
 %09%09%09output.wr
@@ -1292,30 +1292,25 @@
 riteUTF(
-p.getS
+s
 ignature
 ());%0A%09%09%7D
@@ -1301,20 +1301,67 @@
 ignature
-()
 );
+%0A%09%09%09%7D else %7B%0A%09%09%09%09output.writeBoolean(false);%0A%09%09%09%7D
 %0A%09%09%7D%0A%09%7D%0A
@@ -1486,16 +1486,55 @@
 D uuid =
+ Strings.isNullOrEmpty(uuidStr)? null :
  UUID.fr
@@ -1853,32 +1853,63 @@
 nput.readUTF();%0A
+%09%09%09if (input.readBoolean()) %7B%0A%09
 %09%09%09String signat
@@ -1931,16 +1931,17 @@
 dUTF();%0A
+%09
 %09%09%09prope
@@ -1993,16 +1993,85 @@
 ture));%0A
+%09%09%09%7D else %7B%0A%09%09%09%09properties.put(key, new Property(key, value));%0A%09%09%09%7D%0A%0A
 %09%09%7D%0A%0A%09%09r

Fix NPE on GameProfile property without signature