package com.codeski.nbt;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import com.codeski.nbt.tags.NBT;

/**
 * Class for writing NBT structures as NBT, JSON, or XML.
 */
public class NBTWriter {
	private final File file;

	public NBTWriter(File file) throws FileNotFoundException {
		this.file = file;
	}

	/**
	 * Writes the tag specified and its children as JSON text.
	 */
	public void writeJSON(NBT<?> root) {
		try (PrintWriter out = new PrintWriter(file)) {
			out.println("{ " + root.toJSON() + " }");
		} catch (IOException e) {
			System.err.println("There was an error writing the data to JSON text.");
			e.printStackTrace(System.err);
		}
	}

	/**
	 * Writes the tag specified and its children as NBT binary data.
	 */
	public void writeNBT(NBT<?> root) {
		try (DataOutputStream out = new DataOutputStream(new GZIPOutputStream(new FileOutputStream(file)))) {
			out.write(root.toNBT());
		} catch (IOException e) {
			System.err.println("There was an error writing the data to NBT binary data.");
			e.printStackTrace(System.err);
		}
	}

	/**
	 * Writes the tag specified and its children as XML text.
	 */
	public void writeXML(NBT<?> root) {
		try (PrintWriter out = new PrintWriter(file)) {
			out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + root.toXML());
		} catch (IOException e) {
			System.err.println("There was an error writing the data to XML text.");
			e.printStackTrace(System.err);
		}
	}
}

@@ -934,24 +934,133 @@
 %3C?%3E root) %7B%0A
+%09%09this.writeNBT(root, true);%0A%09%7D%0A%0A%09public void writeNBT(NBT%3C?%3E root, boolean compressed) %7B%0A%09%09if (compressed)%0A%09
 %09%09try (DataO
@@ -1150,24 +1150,25 @@
 le)))) %7B%0A%09%09%09
+%09
 out.write(ro
@@ -1176,24 +1176,25 @@
 t.toNBT());%0A
+%09
 %09%09%7D catch (I
@@ -1201,32 +1201,33 @@
 OException e) %7B%0A
+%09
 %09%09%09System.err.pr
@@ -1287,32 +1287,33 @@
 ary data.%22);%0A%09%09%09
+%09
 e.printStackTrac
@@ -1319,32 +1319,304 @@
 ce(System.err);%0A
+%09%09%09%7D%0A%09%09else%0A%09%09%09try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) %7B%0A%09%09%09%09out.write(root.toNBT());%0A%09%09%09%7D catch (IOException e) %7B%0A%09%09%09%09System.err.println(%22There was an error writing the data to NBT binary data.%22);%0A%09%09%09%09e.printStackTrace(System.err);%0A%09
 %09%09%7D%0A%09%7D%0A%0A%09/**%0A%09 *

Allow writing of both compressed and uncompressed NBT data