/*
 * Created on Jul 5, 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 java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;

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

/**
 * @author randrews
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SumsListPanel extends ListPanel{

    Connection conn;
    
    /**
     * @param parent
     * @param conn
     */
    public SumsListPanel(DatabaseWindow parent, Connection conn) {
        super(parent);
        this.conn = conn;
        
        ResultSet res;
        try {
            res = conn.createStatement().executeQuery("select name from sums");
            Vector sums=new Vector();
            while(res.next())
                sums.add(res.getObject("name"));
            fillModel(sums);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        updateWindow();
    }
    
    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumUtil.ListPanel#handleSelection(java.lang.Object)
     */
    public void handleSelection(Object selected) {
        SumsWindow window=new SumsWindow(parent,conn,(String) selected);
        window.setVisible(true);
    }

    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumRunner.ListPanel#deleteElement(java.lang.Object)
     */
    public void deleteElement(Object selectedValue) {
        try{
            conn.createStatement().execute("delete from sums where name=\""+selectedValue+"\"");
            model.removeElement(selectedValue);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumRunner.ListPanel#newElement()
     */
    public void newElement() {
        try{
            String name=(String)JOptionPane.showInputDialog(
                    null,
                    "Name of new field:",
                    "Field name",
                    JOptionPane.PLAIN_MESSAGE);
            if(name==null || name.equals(""))return;
            model.addElement(name);
            conn.createStatement().execute("insert into sums (name) values (\""+name+"\")");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
