/*----------------    FILE HEADER ---------------------------------------
 This file is part of Geoide.
 Copyright (C) 2005-2006 by:
 IDgis B.V.
 http://www.idgis.nl

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

 Contact:

 Herman Assink
 IDgis bv
 P.O. Box 15
 7450 AA Holten
 The Netherlands
 E-Mail: herman.assink@idgis.nl

 * @version 1.4.0
 * @author IDgis team
 * 
 ------------------------------------------------------------------------*/
import nl.idgis.giclient.geoma.Geometry;
import nl.idgis.giclient.geoma.GeometryListener;

class nl.idgis.giclient.geoma.GeometryEventDispatcher {

    private var geometryListeners:Array = null;

    function GeometryEventDispatcher() {
        geometryListeners = new Array();
    }

    function addGeometryListener(geometryListener:GeometryListener):Void {
        geometryListeners.push(geometryListener);
    }

    function removeGeometryListener(geometryListener:GeometryListener):Void {
        for (var i:Number = 0; i < geometryListeners.length; i++) {
            if (geometryListener == geometryListeners[i]) {
                geometryListeners.splice(i, 1);
            }
        }
    }

    function changeGeometry(geometry:Geometry, permanent:Boolean):Void {
        //trace("GeometryEventDispatcher.changeGeometry()");
        updateListeners(geometryListeners);
        for (var i:Number = 0; i < geometryListeners.length; i++) {
            GeometryListener(geometryListeners[i]).onChangeGeometry(geometry, permanent);
        }
    }

    private function updateListeners(listeners:Array):Void {
        for (var i:Number = 0; i < listeners.length; i++) {
            if (listeners[i].toString() == null) { // toString() is necessary as movieclips will never  become null.
                listeners.splice(i--, 1); // i-- because the array that is being looped is also being spliced.
            } else {
                for (var j:Number = 0; j < listeners.length; j++) {
                    if ((listeners[i] == listeners[j]) && (i != j)) {
                        listeners.splice(j--, 1); // j-- because the array that is being looped is also being spliced. i is not affected because j is always greater than i here.
                    }
                }
            }
        }
    }

}