/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */
package com.queplix.core.client.common.event;

import com.google.gwt.user.client.ui.Widget;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Class that sources events.
 *
 * @author Sultan Tezadov
 * @since 26 Nov 2006
 */
// TODO: once generics enabled, remove all occurences of '/*]' and '[*/'
public class EventSource implements SourcesEvents, EventListener {
    private ArrayList/*]<EventListener>[*/ listeners;
    private Widget sender;

    public EventSource(Widget sender) {
        this.sender = sender;
    }

    public void addEventListener(EventListener listener) {
        if(listeners == null) {
            listeners = new ArrayList/*]<EventListener>[*/();
        }
        listeners.add(listener);
    }

    public void removeEventListener(EventListener listener) {
        if(listeners != null) {
            listeners.remove(listener);
        }
    }

    /**
     * Retranslate event
     */
    public void onEvent(Event event, Widget sender) {
        // ignore sender parameter; this.sender will be used instead
        fireEvent(event);
    }

    public void fireEvent(Event event) {
        if(listeners != null) {
            Iterator/*]<EventListener>[*/ iterator = listeners.iterator();
            while(iterator.hasNext()) {
                EventListener listener =
                        /*]/*[*/(EventListener)/*]*[*//*]/[*//*] T[*/ iterator
                        .next();
                listener.onEvent(event, sender);
            }
        }
    }

    public void fireEventGeneratedByUser(Event event) {
        event.setUserGenerated(true);
        fireEvent(event);
        event.setUserGenerated(false); // reset to a safe value
    }

    public void fireEventGeneratedByCode(Event event) {
        event.setUserGenerated(false);
        fireEvent(event);
    }


}
