package com.queplix.core.client.controls.charts;

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

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Image;
import com.queplix.core.client.app.vo.chart.ChartDataItem;
import com.queplix.core.client.app.vo.chart.ChartType;
import com.queplix.core.client.controls.QFormElementModelImpl;
import com.queplix.core.client.controls.QFormElementView;

public abstract class QChartView extends QFormElementView {

    private List listeners = new ArrayList();

    protected QChartView(QFormElementModelImpl model, int layout) {
        super(model, layout);
    }

    public static interface ViewListener {

        void onDataRequested();

        void onEmptyDataRequested();

        void onChartTypeChanged(ChartType type);

        void onClick(ChartDataItem item);

    }

    public void addListener(ViewListener listener) {
        listeners.add(listener);
    }
    
    public void removeListener(ViewListener listener) {
        listeners.remove(listener);
    }

    protected List getListeners(){
        return listeners;
    }

    protected void fireDataRequested() {
        fireEvent(new EventCommand() {
            public void executeEvent(ViewListener listener) {
                listener.onDataRequested();
            }
        });
    }

    protected void fireEmptyDataRequested() {
        fireEvent(new EventCommand() {
            public void executeEvent(ViewListener listener) {
                listener.onEmptyDataRequested();
            }
        });
    }
    
    protected void fireChartTypeChanged(final ChartType type) {
        fireEvent(new EventCommand() {
            public void executeEvent(ViewListener listener) {
                listener.onChartTypeChanged(type);
            }
        });
    }
    
    protected void fireChartClicked(final ChartDataItem item) {
        fireEvent(new EventCommand() {
            public void executeEvent(ViewListener listener) {
                listener.onClick(item);
            }
        });
    }
    
    private void fireEvent(EventCommand command) {
        for (Iterator it = listeners.iterator(); it.hasNext();) {
            ViewListener listener = (ViewListener) it.next();
            command.executeEvent(listener);
        }
    }
    
    private static interface EventCommand {
        abstract void executeEvent(ViewListener listener);
    }

}
