/*
 * MainPanel.java
 *
 * Created on December 1, 2004, 11:58 AM
 */

package DDMT.core;

import java.util.Vector;
import javax.swing.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import DDMT.Nodes.Node;

/**
 *
 * @author  John Kloetzli
 */
public class MainPanel extends javax.swing.JFrame {
    //The list of all the jlabels for the program flow panel
    Vector labels;
    
    //the current label/panel selected selected
    int currLabel = 0;
    
    //The agent that the main panel talks with (Monitor Agent)
    MonitorAgent agent;
    
    //The error stream that writes to this panel's footer panel.
    ControlClass controlClass;
        
    //Index of the current panel
    int currPanel = 0;
    
    /** Creates new form MainPanel */
    public MainPanel(MonitorAgent agent) {
        
        //Record the agent that instantiated this panel
        this.agent = agent;

        //Initialize the GUI components
        initComponents();
        
        //Initialize the ErrorStream
        controlClass = new ControlClass( jTextArea1 );
        
        //Set prefered and minimum size
        this.setBounds(0, 0, 800, 600);
        this.setTitle("DDM Toolkit");
        
        //Set up main scrollpane
        jScrollPane1.getViewport().add(jPanel1);
        
        //Set up program flow panel
        this.showFlow();
    }
    
    //Show the program flow chart
    private void showFlow()
    {   
        
        {            
            //The first panel, the Project Selection panel
            DefaultPanel panel1 = new ProjectSelectionPanel( controlClass );
            jTabbedPane1.add(panel1);

            //Second panel, the New Project Setup panel
            DefaultPanel panel2 = new DDMT.core.NewProjectSetupPanel( controlClass );
            jTabbedPane1.add(panel2);

            //third panel, the Topology Import panel
            DefaultPanel panel3 = new TopologyPanel( controlClass );
            jTabbedPane1.add(panel3);
            
            //Fourth panel, the Agent Types panel
            DefaultPanel panel4 = new AgentTypesPanel(controlClass);
            jTabbedPane1.add(panel4);

            //fifth panel, the Data Import panel
            DefaultPanel panel5 = new DataImportPanel(controlClass);
            jTabbedPane1.add(panel5);

            //Sixth panel, the local monitoring panel
            //DefaultPanel panel6 = new DynamicMonitoringPanel(controlClass);
            //jTabbedPane1.add(panel6);
            
            //seventh panel, the Launch Agents panel
            DefaultPanel panel7 = new LaunchAgentsPanel(controlClass);
            jTabbedPane1.add(panel7);
            
            //Ninth panel, the Final Results panel
            //DefaultPanel panel8 = new FinalResultsPanel();
            //jTabbedPane1.add(panel8);
        }
    }
    
    private void nextPanel()
    {
        if( ((DefaultPanel)jTabbedPane1.getSelectedComponent()).next != null)
        {
            jTabbedPane1.setSelectedComponent(((DefaultPanel)jTabbedPane1.getSelectedComponent()).next);
        }
    }
    
    /**This is the way to tell the MainPanel to show the previous panel in the system.*/
    private void previousPanel()
    {
        if( ((DefaultPanel)jTabbedPane1.getSelectedComponent()).previous != null)
        {
            jTabbedPane1.setSelectedComponent(((DefaultPanel)jTabbedPane1.getSelectedComponent()).previous);
        }
    }
    
    
    /**
     *This class is a output stream for the error display on the main panel as
     *well as the log output file.
     */
    public class ControlClass
    {
        //The text area to output to.
        JTextArea output;
        
        //The file to output to.
        File logFile;
        FileWriter fileWriter;
        BufferedWriter outWriter;
        
        //The projects name
        String name = null;
        
        //The file IO class for the nodes file
        public nodeFileLoader fileLoader;
        
        //The format for the date/time stamp
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss -- ");
        
        //Holds all the nodes that the class uses
        public Node[] nodes;
        
        public ControlClass(JTextArea out){
            
            //Setup the log file
            try
            {    
                output = out;
                logFile = new File("Files\\Core\\log.txt");
                
                fileWriter = new FileWriter(logFile, true);
                outWriter = new BufferedWriter(fileWriter);
            }catch(IOException ex)
            {
                ex.printStackTrace();
            }
            fileLoader = new nodeFileLoader(this);
        }
        
        /*Method that allows the user to display a message to the output stream
         *and save to the log file at the same time.
         */
        public void showError(String errorMsg)
        {

            //Add the date/time stamp
            Date now = new Date();
            errorMsg = dateFormat.format(now)+" "+errorMsg  ;
            
            //Output to the log file
            try
            {
                for( int j = 0; j<errorMsg.length(); j++)
                {
                   outWriter.write((int)errorMsg.charAt(j));
                }
                outWriter.newLine();
                outWriter.flush();
            }catch(IOException ex)
            {
                ex.printStackTrace();
            }
            
            //Output to the program panel
            output.setText(errorMsg +'\n'+ output.getText());
        }
        
        /**
         *This method advances the program to the next panel.
         */
        public void showNextPanel()
        {
            nextPanel();
        }
        
        /**
         *This method returns the program to the previous panel
         */
        public void showPreviousPanel()
        {
            previousPanel();
        }
        
        /**
         *This method sets the name of the current project.
         */
        public void setProjectName( String n )
        {
            this.name = new String(n);
        }
        
        /**
         *This method returns the name of the current project.
         */
        public String getProjectName()
        {
            if( name ==  null)
                return null;
            
            return new String(name);
        }
        
        /**
         *Method to descroy the control class
         */
        public void destroy()
        {
            //Close the output streams
            try{
                outWriter.close();
                fileWriter.close();
            }catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
        
        /**
         *Method to get access to the monitor agent
         */
        public MonitorAgent getAgent()
        {
            return agent;
        }
        
        /**
         *Method to show show the last panel selected
         */
        public void showLastPanel()
        {
            showPanel();
        }
    }
    
    /**
     *Method to show the last panel for this project
     */
    private void showPanel()
    {
        File file = new File("Files\\Projects\\"+controlClass.getProjectName()+"\\CurrentScreen.txt");
        if( !file.exists())
        {
            try{
                //Create it
                file.createNewFile();
            }catch(Exception ex)
            {
                controlClass.showError("Main Panel: Error: Could not create file "+file.getPath());
            }
        }
        //Load the current screen
        else if(controlClass.getProjectName() != null )
        {
            try{
                
                FileReader reader = new FileReader(file);
                BufferedReader bReader = new BufferedReader(reader);
                String line = bReader.readLine();
                
                for( int i = 0; i<jTabbedPane1.getComponentCount(); i++)
                {
                    if( ((DefaultPanel)jTabbedPane1.getComponentAt(i)).getName().equals(line) )
                    {
                        jTabbedPane1.setSelectedComponent(jTabbedPane1.getComponentAt(i));
                        ((DefaultPanel)jTabbedPane1.getSelectedComponent()).refresh();
                        break;
                    }
                }
            }catch(FileNotFoundException ex)
            {
                
            }catch(Exception ex)
            {
                controlClass.showError("Main: Error: Could not read current panel!");
            }
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        jTextArea1 = new javax.swing.JTextArea();

        setName("MainFrame");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jScrollPane1.setFocusable(false);
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel1.setPreferredSize(new java.awt.Dimension(640, 480));
        jPanel1.setMinimumSize(new java.awt.Dimension(640, 480));
        jPanel3.setLayout(new java.awt.BorderLayout());

        jTabbedPane1.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                jTabbedPane1ComponentShown(evt);
            }
        });
        jTabbedPane1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTabbedPane1PropertyChange(evt);
            }
        });
        jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTabbedPane1MouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTabbedPane1MousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTabbedPane1MouseReleased(evt);
            }
        });

        jPanel3.add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.X_AXIS));

        jPanel4.setPreferredSize(new java.awt.Dimension(50, 50));
        jPanel5.setPreferredSize(new java.awt.Dimension(10, 50));
        jPanel5.setMaximumSize(new java.awt.Dimension(10, 50));
        jPanel4.add(jPanel5);

        jButton1.setText("Quit");
        jButton1.setPreferredSize(new java.awt.Dimension(60, 40));
        jButton1.setMaximumSize(new java.awt.Dimension(60, 40));
        jButton1.setMinimumSize(new java.awt.Dimension(60, 40));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel4.add(jButton1);

        jPanel6.setPreferredSize(new java.awt.Dimension(10, 50));
        jPanel6.setMaximumSize(new java.awt.Dimension(10, 50));
        jPanel4.add(jPanel6);

        jPanel7.setLayout(new java.awt.BorderLayout());

        jPanel8.setPreferredSize(new java.awt.Dimension(5, 5));
        jPanel8.setMinimumSize(new java.awt.Dimension(5, 5));
        jPanel7.add(jPanel8, java.awt.BorderLayout.NORTH);

        jPanel9.setPreferredSize(new java.awt.Dimension(5, 5));
        jPanel9.setMinimumSize(new java.awt.Dimension(5, 5));
        jPanel7.add(jPanel9, java.awt.BorderLayout.SOUTH);

        jPanel11.setPreferredSize(new java.awt.Dimension(5, 5));
        jPanel7.add(jPanel11, java.awt.BorderLayout.EAST);

        jPanel10.setLayout(new java.awt.BorderLayout());

        jPanel10.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jTextArea1.setEditable(false);
        jTextArea1.setBackground(new java.awt.Color(233, 236, 216));
        jPanel10.add(jTextArea1, java.awt.BorderLayout.CENTER);

        jPanel7.add(jPanel10, java.awt.BorderLayout.CENTER);

        jPanel4.add(jPanel7);

        jPanel1.add(jPanel4, java.awt.BorderLayout.SOUTH);

        jScrollPane1.setViewportView(jPanel1);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }//GEN-END:initComponents

    private void jTabbedPane1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MousePressed
        
    }//GEN-LAST:event_jTabbedPane1MousePressed

    private void jTabbedPane1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1PropertyChange
        
    }//GEN-LAST:event_jTabbedPane1PropertyChange

    private void jTabbedPane1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseReleased
        
    }//GEN-LAST:event_jTabbedPane1MouseReleased

    /**
     *Method for refreshing the panels that are shown
     */
    private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseClicked
        //Only refresh if the panel changes
        if( currPanel != jTabbedPane1.getSelectedIndex())
        {
            ((DefaultPanel)jTabbedPane1.getSelectedComponent()).refresh();
        
            //Save the current tab selected
            try{
                File file = new File("Files\\Projects\\"+controlClass.getProjectName()+"\\CurrentScreen.txt");
                FileWriter writer = new FileWriter(file);
                BufferedWriter bWriter = new BufferedWriter(writer);
                bWriter.write(((DefaultPanel)jTabbedPane1.getSelectedComponent()).getName());
                bWriter.flush();
                writer.close();
                bWriter.close();
            }catch(Exception ex)
            {
                controlClass.showError("Main Panel: Error: Could not refresh panel!");
            }
        }
        currPanel = jTabbedPane1.getSelectedIndex();
    }//GEN-LAST:event_jTabbedPane1MouseClicked

    private void jTabbedPane1ComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jTabbedPane1ComponentShown
        
    }//GEN-LAST:event_jTabbedPane1ComponentShown

    /**Exit the application*/
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //quit with standard ending
        controlClass.destroy();
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed
    
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        controlClass.destroy();
        System.exit(0);
    }//GEN-LAST:event_exitForm

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
    
}
