package net.robertboehm.ld22;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamedGameMap {

	private StreamedGameMap() {
	}

	public static GameMap fromStream(String name, GameTileset tileset,
			InputStream is) throws IOException {
		int width = -1;
		int height = -1;
		int startX = -1;
		int startY = -1;
		float gravity = -1;
		float friction = -1;
		Tile[] tiles = null;
		GameMapLayer[] layers = null;
		try (DataInputStream dis = new DataInputStream(is)) {
			width = dis.readInt();
			height = dis.readInt();
			gravity = dis.readFloat();
			friction = dis.readFloat();
			layers = new GameMapLayer[dis.readInt()];
			for (int i = 0; i < layers.length; i++) {
				boolean ignoreCollisions = dis.readBoolean();
				boolean special = dis.readBoolean();
				tiles = new Tile[width * height];
				int j = 0;
				int tid;
				if (special) {
					for (int y = 0; y < height; y++) {
						for (int x = 0; x < width; x++) {
							tid = dis.readInt();
							if (tid == 51) {
								// Start
								startX = x;
								startY = y;
							}
							tiles[j++] = null;
						}
					}
				} else {
					for (int y = 0; y < height; y++) {
						for (int x = 0; x < width; x++) {
							tid = dis.readInt();
							tiles[j++] = tid == 0 ? null : tileset.getTile(
									tid - 1, x, y);
						}
					}
				}
				layers[i] = new GameMapLayer(tiles, width, height,
						ignoreCollisions);
			}
		}
		return new GameMap(name, startX, startY, layers, tileset, width,
				height, gravity, friction);
	}

}
