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

import gov.nasa.jsc.plum.PlumUtil.DatabaseWindow;
import gov.nasa.jsc.plum.PlumUtil.ListPanel;
import gov.nasa.jsc.plum.PlumUtil.PlumUtilities;

import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * @author randrews
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class TopologyListPanel extends ListPanel {
    Connection conn;
    
    /**
     * @param parent
     * @param conn
     * @throws java.awt.HeadlessException
     */
    public TopologyListPanel(DatabaseWindow parent, Connection conn)
            throws HeadlessException {
        super(parent);
        this.conn = conn;
        
        updateWindow();
    }


    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumUtil.ListPanel#deleteElement(java.lang.Object)
     */
    public void deleteElement(Object selectedValue) {
        if(selectedValue.equals("default"))
            return;
        try {
            super.deleteElement(selectedValue);
            PlumUtilities.deleteTopology(conn,selectedValue.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumUtil.ListPanel#newElement()
     */
    public void newElement() {
        String name=(String)JOptionPane.showInputDialog(
                null,
                "Name of topology to create:",
                "Topology name",
                JOptionPane.PLAIN_MESSAGE);
        if(name==null || name.equals(""))return;
        
        try{
            PlumUtilities.makeTopology(conn,name);
            model.addElement(name);
        } catch(Exception e){
            e.printStackTrace();
        }
    }


    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumUtil.ListPanel#handleSelection(java.lang.Object)
     */
    public void handleSelection(Object selected) {
        if(selected==null)return;
        JFrame window=new JFrame(selected.toString());
        window.getContentPane().setLayout(new BorderLayout());
        window.getContentPane().add(new TopologyPanel(conn,selected.toString()),BorderLayout.CENTER);

        window.pack();
        window.setVisible(true);
    }
    
    public void updateWindow(){
        try{
            ResultSet res=conn.createStatement().executeQuery("select distinct name from topology");
            Vector names=new Vector();
            while(res.next())
                names.add(res.getString("name"));
            
            fillModel(names);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}
