import MapDesc.TileDesc;
import openfl.display.Sprite;

class Field extends Sprite {
	var tiles:Array<Array<TileEdit>> = [];
	var editor:Main;

	public var mapWidth(default, set):Int;

	function set_mapWidth(value:Int):Int {
		if (tiles.length != value)
			tiles.resize(value);

		for (tx in 0...value) {
			if (tiles[tx] == null) {
				tiles[tx] = [
					for (ty in 0...mapHeight)
						(new TileEdit(editor, tx, ty))
				];

				for (ty in 0...tiles[tx].length) {
					tiles[tx][ty].x = tx * TileEdit.WIDTH;
					tiles[tx][ty].y = ty * TileEdit.HEIGHT;
					addChild(tiles[tx][ty]);
				}
			}
		}

		return mapWidth = value;
	}

	public var mapHeight(default, set):Int;

	function set_mapHeight(value:Int):Int {
		for (tx in 0...tiles.length) {
			if (tiles[tx].length != value) {
				tiles[tx].resize(value);

				for (ty in 0...tiles[tx].length) {
					if (tiles[tx][ty] == null) {
						tiles[tx][ty] = new TileEdit(editor, tx, ty);
						tiles[tx][ty].x = tx * TileEdit.WIDTH;
						tiles[tx][ty].y = ty * TileEdit.HEIGHT;
						addChild(tiles[tx][ty]);
					}
				}
			}
		}

		return mapHeight = value;
	}

	public var tileDescs(get, never):Array<Array<TileDesc>>;

	function get_tileDescs():Array<Array<TileDesc>> {
		return [
			for (tx in 0...tiles.length) [for (ty in 0...tiles[tx].length) tiles[tx][ty].tileDesc]
		];
	}

	public function setTiles(tilesData:Array<Array<TileDesc>>) {
		for (tx in 0...mapWidth) {
			for (ty in 0...mapHeight) {
				tiles[tx][ty].setTileData(tilesData[tx][ty]);
			}
		}
	}

	public function new(editor:Main, initWidth:Int, initHeight:Int) {
		super();

		this.editor = editor;

		mapWidth = initWidth;
		mapHeight = initHeight;
	}
}
