package net.lax1dude.eaglercraft.beta;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.Charset;

import com.jcraft.jzlib.Deflater;
import com.jcraft.jzlib.DeflaterOutputStream;

import net.lax1dude.eaglercraft.SHA1Digest;

public class EPKCompiler {
	
	private final ByteArrayOutputStream osb = new ByteArrayOutputStream();
	private DataOutputStream os;
	private Deflater d;
	private final SHA1Digest dig = new SHA1Digest();
	
	public EPKCompiler(String name) {
		try {
			d = new Deflater(9);
			os = new DataOutputStream(osb);
			os.write("EAGPKG!!".getBytes(Charset.forName("UTF-8")));
			os.writeUTF("\n\n #  eaglercraft package file - " + name + "\n #  eagler eagler eagler eagler eagler eagler eagler\n\n");
			d = new Deflater(9);
			os = new DataOutputStream(new DeflaterOutputStream(osb, d));
		}catch(Throwable t) {
			throw new RuntimeException("this happened somehow", t);
		}
	}
	
	public void append(String name, byte[] dat) {
		try {
			os.writeUTF("<file>");
			os.writeUTF(name);
			byte[] v = dat;
			dig.update(v, 0, v.length);
			byte[] final_ = new byte[20];
			dig.doFinal(final_, 0);
			os.write(final_);
			os.writeInt(v.length);
			os.write(v);
			os.writeUTF("</file>");
		}catch(Throwable t) {
			throw new RuntimeException("this happened somehow", t);
		}
	}
	
	public byte[] complete() {
		try {
			os.writeUTF(" end");
			os.flush();
			os.close();
			return osb.toByteArray();
		}catch(Throwable t) {
			throw new RuntimeException("this happened somehow", t);
		}
	}
	
}
