/*
 * 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;
import gov.nasa.jsc.plum.DBManager.Database;
import gov.nasa.jsc.plum.PlumUtil.DatabaseWindow;
import gov.nasa.jsc.plum.PlumUtil.PlumMenu;
import gov.nasa.jsc.plum.Reports.DDCUReport;
import gov.nasa.jsc.plum.Reports.ExpressReport;
import gov.nasa.jsc.plum.Reports.InterfaceReport;
import gov.nasa.jsc.plum.Reports.RackInputReport;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * @author randrews
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class PlumWindowMenu extends JMenuBar implements PlumMenu{
    Connection conn;
    DatabaseWindow parent;
    
    public PlumWindowMenu(){
        JMenu window=new JMenu("Window");
        JMenu database=new JMenu("Database");
        JMenu setup=new JMenu("Setup");
        JMenu reports=new JMenu("Reports");
        
        JMenuItem programs=new JMenuItem("External Programs...");
        programs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,KeyEvent.CTRL_MASK,false));
        programs.addActionListener(new ProgramsAL());
        
        JMenuItem runs=new JMenuItem("Runs");
        runs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,KeyEvent.CTRL_MASK,false));
        runs.addActionListener(new RunsAL());

        JMenuItem constraints=new JMenuItem("Constraints");
        constraints.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,KeyEvent.CTRL_MASK,false));
        constraints.addActionListener(new ConstraintsAL());

        JMenuItem sums=new JMenuItem("Straight-Sum Fields");
        sums.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U,KeyEvent.CTRL_MASK,false));
        sums.addActionListener(new SumsAL());

        JMenuItem singlecombo=new JMenuItem("Single Combination");
        singlecombo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,KeyEvent.CTRL_MASK,false));
        singlecombo.addActionListener(new SingleComboAL());

        JMenuItem save=new JMenuItem("Save");
        save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,KeyEvent.CTRL_MASK,false));
        save.addActionListener(new SaveAL());

        JMenuItem load=new JMenuItem("Load");
        load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,KeyEvent.CTRL_MASK,false));
        load.addActionListener(new LoadAL());

        JMenuItem rackdata=new JMenuItem("Rack Data");
        rackdata.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,KeyEvent.CTRL_MASK,false));
        rackdata.addActionListener(new RackDataAL());
        
        JMenuItem topology=new JMenuItem("Topology list");
        topology.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,KeyEvent.CTRL_MASK,false));
        topology.addActionListener(new TopologyAL());
        
        JMenuItem newfield=new JMenuItem("Add new field");
        newfield.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,KeyEvent.CTRL_MASK,false));
        newfield.addActionListener(new NewFieldAL());

        
        ReportsAL reportsal=new ReportsAL();
        
        JMenuItem ddcu=new JMenuItem("DDCU");
        ddcu.addActionListener(reportsal);
        reports.add(ddcu);
        
        JMenuItem interfaces=new JMenuItem("Interfaces");
        interfaces.addActionListener(reportsal);
        reports.add(interfaces);

        JMenuItem rackinput=new JMenuItem("Rack Input Data");
        rackinput.addActionListener(reportsal);
        reports.add(rackinput);

        JMenuItem express=new JMenuItem("EXPRESS Table");
        express.addActionListener(reportsal);
        reports.add(express);

        JMenu individual=new JMenu("Individual Resource Reports...");
        reports.add(individual);

        TreeMap indreports=new TreeMap();
        indreports.put("Acoustics","1");
        indreports.put("Middecks","racks.mid_resupply");
        indreports.put("Stowage","racks.stowage");
        indreports.put("Crew Time","racks.crew_time");
        indreports.put("Crew Training","racks.crew_training");
        indreports.put("Energy","racks.energy");
        indreports.put("Keep-Alive Power","racks.keepalive_power");
        indreports.put("Launch Upmass","racks.upmass_resupply");
        indreports.put("LTL Flow Rate","racks.LTL_flow");
        indreports.put("MTL Flow Rate","racks.MTL_flow");
        indreports.put("Operating Time","racks.hrs_per_cycle*racks.cycles_per_increment");
        indreports.put("Power","racks.power");
        
        IndividualAL individualal=new IndividualAL(indreports);

        Iterator i=indreports.keySet().iterator();
        while(i.hasNext())
        {
            JMenuItem item=new JMenuItem(i.next().toString());
            individual.add(item);
            item.addActionListener(individualal);
        }
        
        database.add(save);
        database.add(load);

        window.add(runs);
        window.add(constraints);
        window.add(singlecombo);
        window.add(sums);
        window.add(rackdata);
        window.add(topology);
        window.add(newfield);

        setup.add(programs);
        
        add(database);
        add(setup);
        add(window);
        add(reports);
    }

    public void setConnection(Connection conn){
        this.conn=conn;
    }

    public void setParent(DatabaseWindow parent){
        this.parent=parent;
    }
    
    private class ReportsAL implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            String report=((JMenuItem)arg0.getSource()).getText();
            if(report.equals("DDCU"))
            {
                JFileChooser chooser = new JFileChooser(parent.getCfg().getOutput());
                chooser.setSelectedFile(new File("ddcu.xls"));
                int returnVal = chooser.showSaveDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION)
                {
                    String fname=chooser.getSelectedFile().getAbsolutePath();
                    parent.log("Writing DDCU report to file...\n");
                    DDCUReport ddcu=new DDCUReport(conn,fname);
                    parent.log("Finished\n\n");
                }          
            }
            else if(report.equals("Interfaces"))
            {
                JFileChooser chooser = new JFileChooser(parent.getCfg().getOutput());
                chooser.setSelectedFile(new File("interfaces.html"));
                int returnVal = chooser.showSaveDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION)
                {
                    String fname=chooser.getSelectedFile().getAbsolutePath();
                    parent.log("Writing interface report to file...\n");
                    InterfaceReport iface=new InterfaceReport(conn,fname);
                    parent.log("Finished\n\n");
                }          
            }
            else if(report.equals("Rack Input Data"))
            {
                JFileChooser chooser = new JFileChooser(parent.getCfg().getOutput());
                chooser.setSelectedFile(new File("rackinput.xls"));
                int returnVal = chooser.showSaveDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION)
                {
                    String fname=chooser.getSelectedFile().getAbsolutePath();
                    parent.log("Writing rack input data to file...\n");
                    RackInputReport iface=new RackInputReport(conn,fname);
                    parent.log("Finished\n\n");
                }          
            }
            else if(report.equals("EXPRESS Table"))
            {
                JFileChooser chooser = new JFileChooser(parent.getCfg().getOutput());
                chooser.setSelectedFile(new File("express.xls"));
                int returnVal = chooser.showSaveDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION)
                {
                    String fname=chooser.getSelectedFile().getAbsolutePath();
                    parent.log("Writing rack input data to file...\n");
                    ExpressReport express=new ExpressReport(conn,fname);
                    parent.log("Finished\n\n");
                }                          
            }
            else
            {
                System.out.println("\""+report+"\" is not a valid report. Did the string get changed? Look in PlumMenu.java");
            }
        }
    }
    
    private class IndividualAL implements ActionListener {
        TreeMap indreports;
        public IndividualAL(TreeMap indreports){
            this.indreports=indreports;
        }
        
        public void actionPerformed(ActionEvent arg0) {
            String report=((JMenuItem)arg0.getSource()).getText();
            String field=indreports.get(report).toString();
            
            JFileChooser chooser = new JFileChooser(parent.getCfg().getOutput());
            chooser.setSelectedFile(new File(report+".xls"));
            int returnVal = chooser.showSaveDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION)
            {
                String fname=chooser.getSelectedFile().getAbsolutePath();
                parent.log("Writing resource report to file...\n");
                try {
                    ResultSet res=conn.createStatement().executeQuery("select racks.acronym as acronym,modules.acronym as modname, "+field+" as field from racks,locations,modules where racks.location=locations.idx and locations.module=modules.idx");
                    FileWriter out=new FileWriter(fname);
                    out.write("Acronym\tModule");
                    if(!report.equals("Acoustics"))
                        out.write("\t"+report);
                    out.write("\n");
                    while(res.next())
                    {
                        out.write(res.getString("acronym")+"\t"+res.getString("modname"));
                        if(!report.equals("Acoustics"))
                            out.write("\t"+res.getObject("field").toString());
                        out.write("\n");
                    }
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                parent.log("Finished\n\n");
            }                          
        }
    }
    
    private class RunsAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("Runs");
            window.getContentPane().add(new RunListPanel(parent,conn));
            window.pack();
            window.setVisible(true);
        }
    }
    
    
    private class RackDataAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            StationWindow window=new StationWindow(conn,parent);
            window.setVisible(true);
        }
    }
    
    private class TopologyAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("Topology list");
            window.getContentPane().add(new TopologyListPanel(parent,conn));
            window.pack();
            window.setVisible(true);
        }
    }

    private class NewFieldAL implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            NewFieldDialog dialog=new NewFieldDialog(conn,parent);
            dialog.setVisible(true);
        }
        
    }
    

    private class ConstraintsAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("Constraints");
            window.getContentPane().add(new ConstraintListPanel(parent,conn));
            window.pack();
            window.setVisible(true);            
        }
    }

    private class SumsAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("Straight-Sum Fields");
            window.getContentPane().add(new SumsListPanel(parent,conn));
            window.pack();
            window.setVisible(true);            
        }
    }
    
    private class SingleComboAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("Single Combination");
            window.getContentPane().add(new SingleComboPanel(parent,conn));
            window.pack();
            window.setVisible(true);            
        }
    }

    private class ProgramsAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame window=new JFrame("External programs");
            window.getContentPane().add(new ProgramPanel(parent));
            window.pack();
            window.setVisible(true);            
        }
    }

    private class SaveAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showSaveDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION)
            {
                String fname=chooser.getSelectedFile().getAbsolutePath();
                parent.log("Saving to file "+fname);
                Database db=new Database(conn,true,true);
                db.toFile(fname);
                parent.log("Finished saving.");
            }
        }
    }

    private class LoadAL implements ActionListener {
        public void actionPerformed(ActionEvent e){
            try{
                JFileChooser chooser = new JFileChooser();
                String fname=null;
                if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
                    fname=chooser.getSelectedFile().getAbsolutePath();
                else return;
                
                ResultSet tables=conn.createStatement().executeQuery("show tables");
                String query="drop table ";
                boolean comma=false;
                while(tables.next())
                {
                    if(comma)query+=", ";
                    else comma=true;
                    String tbl=tables.getString(1);
                    query+=tbl;
                }
                if(comma) // This will do nothing if there were no tables.
                    conn.createStatement().execute(query);
                
                BufferedReader filein=new BufferedReader(new FileReader(fname));
                String line=null;
                Statement stmt=conn.createStatement();
                while((line=filein.readLine())!=null)
                {
                    if(line.startsWith("#"))continue; // Skip comments
                    if(!line.endsWith(";"))line=line+";";
//                    System.out.println(line);
                    stmt.execute(line);
                }
                filein.close();
                
                parent.log("Finished loading from "+fname);
            } catch(Exception e1){
                e1.printStackTrace();
                parent.log("SQL Error while loading:\n"+e1.getMessage());
            }
        }
    }
}
