package com.approximatrix.draco.fit.ui;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.event.EventListenerList;

import com.approximatrix.draco.application.worker.WorkerEvent;
import com.approximatrix.draco.application.worker.WorkerListener;
import com.approximatrix.draco.fit.LSFit;
import com.sun.java.SwingWorker;

public abstract class ProgressDialog extends JDialog {

	protected SwingWorker worker = null;
	
	/** The listener list. */
    protected EventListenerList listener = new EventListenerList();
   
    protected LSFit analysis = null;
    
	public ProgressDialog(JFrame master) {
		super(master,true);
	}
	
	public void start() {
		if(worker == null) return;
		worker.start();
		this.setVisible(true);	
	}
	
	/** Removes a WorkerListener.
     * @param l the WorkerListener
     */
    public void removeWorkerListener(WorkerListener l) {
        listener.remove(WorkerListener.class, l);
    }
    
    /** Adds a WorkerListener.
     * @param l the WorkerListener
     */
    public void addWorkerListener(WorkerListener l) {
    	/** Look for duplicates */
        Object[] ls = listener.getListenerList();
        boolean found = false;
        for(int i = ls.length-1; i >= 1; i-=2) {
        	if(ls[i] == l) {
        		found = true;
        		break;
        	}
        }
		if(!found)
	        listener.add(WorkerListener.class, l);
    }
    
    /** Clears all WorkerListeners from the object */
   	public void clearWorkerListener() {
   		listener = new EventListenerList();
   	}
   	
   	protected void fireWorkerEvent() {
   		WorkerEvent rce = new WorkerEvent(this, this.analysis);
        Object[] ls = listener.getListenerList();
        for (int i = (ls.length - 2); i >= 0; i-=2) {
            if (ls[i] == WorkerListener.class) {
                ((WorkerListener)ls[i + 1]).workerRequest(rce);
            }
        }	
   	}  
}
