/*
 * Created on Jan 27, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.nasa.jsc.plum.PlumUtil;
import gov.nasa.jsc.plum.Configuration;

import java.io.PrintStream;
import java.sql.Connection;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * @author randrews
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DatabaseWindow extends JFrame{
    Connection conn;
    JTextArea debug;
    Configuration cfg;
    Vector windows;
    
    public DatabaseWindow(Connection conn, String menuclass,boolean debugout,String title) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
        super(title);
        windows=new Vector();
        cfg=new Configuration();
        this.conn=conn;
        debug=new JTextArea();
        debug.setRows(10);
        debug.setColumns(35);
        debug.setEditable(false);
        getContentPane().add(new JScrollPane(debug));
        Object obj=Class.forName(menuclass).newInstance();
        if(obj instanceof PlumMenu)
        {
            PlumMenu menu=(PlumMenu)obj;
            menu.setConnection(conn);
            menu.setParent(this);
            if(menu instanceof JMenuBar)
                setJMenuBar((JMenuBar)menu);
        }
        
        PrintStream newout=new PrintStream(new TextAreaOutput(debug));
        System.setOut(newout);
        if(debugout)
            System.setErr(newout);
        
        pack();
    }
    
    public void log(String message){
        debug.append(message);
        if(!message.endsWith("\n"))
            debug.append("\n");
    }

    protected class AsynchUpdater implements Runnable{
        public void run() {
            Iterator i=windows.iterator();
            while(i.hasNext())
            {
                Object window=i.next();
                if(window instanceof Updateable)
                    ((Updateable)window).updateWindow();
            }
        }
    }
    
    /**
     * @return Returns the cfg.
     */
    public Configuration getCfg() {
        return cfg;
    }
    
    public void updateWindows(){
        javax.swing.SwingUtilities.invokeLater(new AsynchUpdater());
    }
    
    public void addWindow(Object window){
        if(!windows.contains(window))
            windows.add(window);
    }
    
    public void removeWindow(Object window){
        windows.remove(window);
    }
}
