/*
 * Created on Feb 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 gov.nasa.jsc.plum.PlumUtil.DatabaseWindow;
import gov.nasa.jsc.plum.PlumUtil.ListPanel;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

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 ConstraintListPanel extends ListPanel{
    Connection conn;
    
    
    /**
     * @param parent
     * @param conn
     */
    public ConstraintListPanel(DatabaseWindow parent, Connection conn) {
        super(parent);
        this.conn = conn;
        updateWindow();
    }
    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumRunner.ListPanel#deleteElement(java.lang.Object)
     */
    public void deleteElement(Object selectedValue) {
        try{
            conn.createStatement().execute("delete from constraints where name=\""+selectedValue+"\"");
            conn.createStatement().execute("delete from runcons where cons=\""+selectedValue+"\"");
            conn.createStatement().execute("delete from comments where tblname=\"constraints\" and value=\""+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 constraint:",
                    "Constraint name",
                    JOptionPane.PLAIN_MESSAGE);
            if(name==null || name.equals(""))return;
            model.addElement(name);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * @see gov.nasa.jsc.plum.PlumRunner.ListPanel#handleSelection(java.lang.Object)
     */
    public void handleSelection(Object selected) {
        ConstraintWindow window=new ConstraintWindow(parent,conn,(String) selected);
        window.setVisible(true);
    }
    
    public void updateWindow(){
        try{
            Vector names=new Vector();
            ResultSet res=conn.createStatement().executeQuery("select distinct name from constraints");
            while(res.next())
                names.add(res.getString("name"));
            
            fillModel(names);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
