import js.Browser;
import js.html.Node;
import haxe.io.Bytes;
import haxe.io.BytesOutput;
import haxe.zip.Writer;
import haxe.zip.Entry;
import haxe.crypto.Crc32;
import haxe.crypto.Base64;

@:expose
class JsZip {
	public static function zip(id : String, foldername : String) : String {
		var div : Node = Browser.document.getElementById(id).firstChild;
		var entries : List<Entry> = new List();
		var i : Int = 0;
		while (i < div.childNodes.length) {
			var codename : String = div.childNodes.item(i).textContent;
			var code : String = div.childNodes.item(i + 1).textContent;
			var bytes : Bytes = Bytes.ofString(code);
			var entry : Entry = {
				fileName: foldername + "/" + codename,
				fileSize: bytes.length,
				fileTime: Date.now(),
				compressed: false,
				dataSize: 0,
				data: bytes,
				crc32: Crc32.make(bytes)
			};
			entries.push(entry);
			i += 2;
		}
		var output = new BytesOutput();
		var zipWriter = new Writer(output);
		zipWriter.write(entries);
		return Base64.encode(output.getBytes());
	}
}
