/// <reference path="Relations/RelationOneToMany.ts" />
class Region {
    public name : string;

    public constructor (name : string) {
        this.name = name;
    }

    public static RegionRoom = new RelationOneToMany();
    public static RegionRegion = new RelationOneToMany();
    public static InRelation = new RelationHandlerStrictOneToMany(Region.RegionRegion, Region.RegionRoom);

    public place (...rooms : Array<Room | Region>) {
        rooms.forEach(room => {
            if (room instanceof Room) {
                Region.RegionRoom.setRelation(this, room);
            } else {
                Region.RegionRegion.setRelation(this, room);
            }
        });
    }

    public getRooms () {
        let rooms = <Array<Room>> Region.RegionRoom.getRight(this);
        Region.RegionRegion.getRight(this).forEach((region : Region) => {
            (<Array<Room>> Region.RegionRoom.getRight(region)).forEach((room : Room) => {
                rooms.push(room);
            });
        });
        return rooms;
    }

    public containsRoom (room : Room) {
        let directlyContained = Region.RegionRoom.getLeft(room) == this;
        if (directlyContained) {
            return true;
        } else if (Region.RegionRegion.getLeft(this) != undefined) {
            return this.getRooms().indexOf(room) != -1; // If it's not directly contained, we have to check rooms for every region that contains this one and I don't care enough to do that right now
            // TODO: optimize this.
        }
        return false;
    }

    public contains (thing : Thing) {
        let room = thing.getRoom();
        if (room == undefined) {
            return false;
        } else {
            let regions = Region.InRelation.getAllLeft(room);
            return regions.indexOf(this) != -1;
        }
    }
}