/*
 * Created on Apr 4, 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.Configuration;
import gov.nasa.jsc.plum.PlumUtil.DatabaseWindow;
import gov.nasa.jsc.plum.PlumUtil.PlumUtilities;
import gov.nasa.jsc.plum.PlumUtil.TextAreaOutput;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.TreeMap;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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 SingleComboPanel extends JPanel implements ActionListener {

    DatabaseWindow parent;
    Connection conn;
    
    JCheckBox sams;
    JComboBox runs;
    TreeMap runtable;
    Vector racks;
    
    /**
     * @param parent
     * @param conn
     */
    public SingleComboPanel(DatabaseWindow parent, Connection conn) {
        this.parent=parent;
        this.conn=conn;
        try{
            drawPanel();
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    protected void drawPanel() throws Exception{
        TreeMap labels=new TreeMap();

        ResultSet res;
        res=conn.createStatement().executeQuery("select acronym, idx from racks order by idx asc");

        ResultSetMetaData md=res.getMetaData();
        JPanel widgetPanel=new JPanel();
        widgetPanel.setLayout(new GridBagLayout());
        
        racks=new Vector();
        
        GridBagConstraints c=new GridBagConstraints();
        c.gridy=0;
        c.anchor=GridBagConstraints.WEST;

        while(res.next())
        {
            JCheckBox entry=new JCheckBox();
            racks.add(entry);

            c.gridx=0;
            widgetPanel.add(new JLabel(res.getString("acronym")),c);
            c.gridx=1;
            widgetPanel.add(entry,c);
            c.gridy++;            
        }
        
        JPanel buttons=new JPanel();
        buttons.setLayout(new GridBagLayout());
        
        runs=new JComboBox();
        runtable=new TreeMap();
        res=conn.createStatement().executeQuery("select name,idx from runs");
        while(res.next())
        {
            runs.addItem(res.getString("name"));
            runtable.put(res.getObject("name"),res.getObject("idx"));
        }
        c.gridx=0;
        c.gridy=0;
        c.gridwidth=2;
        c.weightx=1;
        buttons.add(runs,c);
        
        sams=new JCheckBox();
        c.gridx=0;
        c.gridy=1;
        c.gridwidth=1;
        c.weightx=0;
        buttons.add(new JLabel("Needs SAMS: "),c);
        c.gridx=1;
        buttons.add(sams,c);
        
        JButton run=new JButton("Run");
        run.addActionListener(this);
        c.gridy=2;
        c.gridx=0;
        c.gridwidth=2;
        buttons.add(run,c);
        
        setLayout(new BorderLayout());
        
        JScrollPane scroll=new JScrollPane(widgetPanel);
        Dimension size=scroll.getPreferredSize();
//        size.width+=50;
        size.height=600;
        scroll.setPreferredSize(size);
        
        add(scroll,BorderLayout.CENTER);
        add(buttons,BorderLayout.SOUTH);
    }

    private class SingleComboResultsWindow extends JFrame{

        private JTextArea results;
        
        /**
         * @param racks
         * @param b
         */
        public SingleComboResultsWindow() {
            super("Single Combination Results");
            results=new JTextArea();
            results.setRows(25);
            results.setColumns(50);
            results.setEditable(false);
            runCombo();
            JScrollPane scroll=new JScrollPane(results);
            Dimension size=scroll.getPreferredSize();
            size.width+=50;
            size.height=600;
            scroll.setPreferredSize(size);
            getContentPane().add(scroll);
            pack();
            setVisible(true);
        }
        
        private void runCombo(){
            String combo="";
            for(int n=0;n!=racks.size();n++)
                if(((JCheckBox)racks.get(n)).isSelected())
                    combo+="1";
                else
                    combo+="0";
            
            String topology=null;
            try{
                ResultSet res=conn.createStatement().executeQuery("select topology from runs where name=\""+runs.getSelectedItem()+"\"");
                res.next();
                topology=res.getString(1);
            }catch(Exception e){
                e.printStackTrace();
            }
            
            Integer idx=(Integer) runtable.get(runs.getSelectedItem());
            Configuration config=parent.getCfg();
            String calc=config.getPrograms();
            if(config.getDelimiter().equals("slash"))
                calc+="/";
            else if(config.getDelimiter().equals("backslash"))
                calc+="\\";
            calc+=config.getSingle();
            String cmd=ProgressWindow.staticParse(calc,idx.intValue());
            cmd=cmd.replaceAll("\\$combo",combo);
            cmd=cmd.replaceAll("\\$sams",(sams.isSelected()?"1":"0"));

            
            SingleRunner sr=new SingleRunner(cmd,new TextAreaOutput(results));

            if(topology!=null)
                PlumUtilities.setTopology(conn,topology);

            sr.start();
        }
        
        private class SingleRunner extends Thread{
            private String cmd;
            private PrintStream out;
            
            public SingleRunner(String cmd,OutputStream out){
                this.cmd=cmd;
                this.out=new PrintStream(out);
            }
            
            public void run(){
                try {
                    out.print("Running command:\n"+cmd+"\n------------------------\n");
                    
                    Process proc=Runtime.getRuntime().exec(cmd); // Do cool stuff with error output redirection.
                    BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                    BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                    String line="",error="";
                    while ((line=stdout.readLine())!=null || (error=stderr.readLine())!=null)
                    {
                        if(!line.equals(""))
                            out.println(line);
                        if(!error.equals(""))
                            out.println(error);
                        line=error="";
                    }
                    
                    proc.waitFor();
                } catch(IOException e){
                    out.print("\n"+cmd+"\ndoes not exist.");
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally
                {
                    PlumUtilities.setTopology(conn,"default");
                }
           }
        }

    }
        
    
    /* (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent arg0) {
        JFrame window=new SingleComboResultsWindow();
    }

}
