package model;

import haxe.ds.StringMap;

class Diagram {
	public var sets : StringMap<Set>;
	public var associations : StringMap<Association>;

	//drawing informations
	public var width : Int;
	public var height : Int;

	public function new() {
		sets = new StringMap();
		associations = new StringMap();
		height = 0;
		width = 0;
	}

	public function getObj(name : String) : Set {
		var o : Set = sets.get(name);
		if (o == null) {
			o = associations.get(name);
		}
		return o;
	}

	public function iterator() : Iterator<Set> {
		return new ObjectsIterator(this);
	}

	public function getGrid() : Array<Array<Set>> {
		var grid : Array<Array<Set>> = [ for (row in 0...height) [ for (col in 0...width) null ] ];
		for (o in this) {
			grid[o.row][o.col] = o;
		}
		return grid;
	}

	public function loadGrid(grid : Array<Array<Set>>) {
		height = grid.length;
		width = height == 0 ? 0 : grid[0].length;
		for (row in 0...grid.length) {
			for (col in 0...grid[row].length) {
				if (grid[row][col] != null) {
					grid[row][col].row = row;
					grid[row][col].col = col;
				}
			}
		}
	}
}

class ObjectsIterator {
	var objects : Array<Set>;
	var i : Int;

	public function new(diagram : Diagram) {
		var sets : Array<Set> = Lambda.array(diagram.sets);
		var associations : Array<Set> = cast Lambda.array(diagram.associations);
		objects = Lambda.concat(sets, associations);
		i = 0;
	}

	public function hasNext() : Bool {
		return i != objects.length;
	}

	public function next() : Set {
		i++;
		return objects[i - 1];
	}
}
