/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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);
            }
        }	
   	}  
}
