/*
This software was created by United States Government employees at 
The Center for Cybersecurity and Cyber Operations (C3O) 
at the Naval Postgraduate School NPS.  Please note that within the 
United States, copyright protection is not available for any works 
created  by United States Government employees, pursuant to Title 17 
United States Code Section 105.   This software is in the public 
domain and is not subject to copyright. 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
 */
package labtainers.paramsui;

import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import labtainers.mainui.MainWindow;
import labtainers.goalsui.GoalsData;
import labtainers.goalsui.GoalsUI;

/**
 *
 * @author Daniel Liao
 */
public class ParamsUI extends javax.swing.JFrame {

    /**
     * Creates new form NewJDialog
     */
    ParamsData data;
    ParamsData saved;
    MainWindow mainUI;
    
    public ParamsUI(java.awt.Frame parent, boolean modal) {
        //super(parent);
        initComponents();
        this.setVisible(true);
        paramsScrollPaneBar = ScrollPaneOfParams.getVerticalScrollBar();
        
        this.mainUI = (MainWindow)parent;
        this.data = new ParamsData(this.mainUI.getCurrentData().getParamsData());
        this.saved = new ParamsData(this.data);
        
        loadUI();
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ScrollPaneOfParams = new javax.swing.JScrollPane();
        PanelofParams = new javax.swing.JPanel();
        CreateButton = new javax.swing.JButton();
        RemoveAllButton = new javax.swing.JButton();
        UpdateButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Results Configuration");
        setMinimumSize(new java.awt.Dimension(1590, 500));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        PanelofParams.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
        ScrollPaneOfParams.setViewportView(PanelofParams);

        CreateButton.setText("Create");
        CreateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateButtonActionPerformed(evt);
            }
        });

        RemoveAllButton.setText("Remove All");
        RemoveAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveAllButtonActionPerformed(evt);
            }
        });

        UpdateButton.setText("OK");
        UpdateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UpdateButtonActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel5.setText("Operator");
        jLabel5.setToolTipText("File should either be a file path or a program/utility name with the \".stdin\", \".stdout\", or \".prgout\" extension.\n\n Ex. \"test.stdin\", \".local/result/sniff.txt\" ");

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel1.setText("Param ID");
        jLabel1.setToolTipText("The symbolic name of the result, which will be referenced in the goals configuration file. \n\n(It must be alphanumeric, underscores permitted) ");

        CancelButton.setText("Cancel");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 12, Short.MAX_VALUE)
                        .addComponent(ScrollPaneOfParams, javax.swing.GroupLayout.PREFERRED_SIZE, 1566, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(CreateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(RemoveAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(91, 91, 91)
                                .addComponent(jLabel1)
                                .addGap(104, 104, 104)
                                .addComponent(jLabel5)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(542, 542, 542)
                .addComponent(UpdateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(CancelButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CreateButton)
                    .addComponent(RemoveAllButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ScrollPaneOfParams, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(UpdateButton)
                    .addComponent(CancelButton))
                .addContainerGap(39, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CreateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateButtonActionPerformed
       createButton();
    }//GEN-LAST:event_CreateButtonActionPerformed
    
    private void RemoveAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveAllButtonActionPerformed
        removeAllButton();
    }//GEN-LAST:event_RemoveAllButtonActionPerformed

    private void UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateButtonActionPerformed
        updateButton();
    }//GEN-LAST:event_UpdateButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
       mainUI.setParamsClosed();
    }//GEN-LAST:event_formWindowClosing

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
       mainUI.setParamsClosed();
       setVisible(false);
       dispose(); 
    }//GEN-LAST:event_CancelButtonActionPerformed

    // BUTTONS //
    
    // Adds a new param panel
    private void createButton(){
        addParamsPanel(new ParamPanels(this, data.rowCount+1));
        paramsScrollPaneBar.setValue(paramsScrollPaneBar.getMaximum());
    }
    
    // Updates the param data object basd on the current param configuration UI state
    private void updateButton(){
        System.out.println("Update button");
        data.updateListofParams(PanelofParams);
        if(data.writeParamsConfig(true) != null){
            saved = new ParamsData(data);
            this.mainUI.getCurrentData().setParamsData(saved);
            this.mainUI.updateParameters();
        }
        mainUI.setParamsClosed();
        setVisible(false);
        dispose(); 
    }
    
    // Removes all the param panels
    private void removeAllButton(){
       if(JOptionPane.showConfirmDialog(null, "Are you sure you want to remove all?") == JOptionPane.YES_OPTION){
            removeAllParams();
       }          
    }
    
    
    // CORE FUNCTIONS//
      
    // Adds param panel
    public int paramsPanePanelLength = 0;
    private JScrollBar paramsScrollPaneBar;
    private void addParamsPanel(ParamPanels panel){
        //Resize the JPanel Holding all the ParamsPanels to fit another one (makes the scroll bar resize and should show all objects listed)
        paramsPanePanelLength+=panel.getPreferredSize().height+5;
        PanelofParams.setPreferredSize(new Dimension(0,paramsPanePanelLength));
        
        // Create the Param Panel and add it
        data.rowCount++;
        PanelofParams.add(panel); //takes in parent(this), containerlist, rowcount
        
        // Redraw GUI with the new Panel
        PanelofParams.revalidate();
        PanelofParams.repaint(); 
    }    
    
    // Removes all the param lines for the lab *note: this doesn't update parameter.config or the paramsData until the user hits the update button
    private void removeAllParams(){
        data.rowCount = 0;
        paramsPanePanelLength = 0;
        PanelofParams.setPreferredSize(new Dimension(0,paramsPanePanelLength));
        Component[] componentList = PanelofParams.getComponents();
        for(Component c: componentList){
            PanelofParams.remove(c);
        }

        PanelofParams.revalidate();
        PanelofParams.repaint();
    }
    
    // loads the param panels based on the current data
    protected void loadUI(){
        removeAllParams();               
        //redraw the param
        for(int i=0; i < data.listofParams.size(); i++)
            loadParam(data.listofParams.get(i), i+1);
    }
    
    // Load the param panel into GUI
    private void loadParam(ParamValues paramVal, int rowNum){
        ParamPanels newParam = new ParamPanels(this, rowNum,
                                                        paramVal.paramID, 
                                                        paramVal.fileList, 
                                                        paramVal.operator, 
                                                        paramVal.symbol, 
                                                        paramVal.hashedString, 
                                                        paramVal.upperBound, 
                                                        paramVal.lowerBound,
                                                        paramVal.step,
                                                        paramVal.comments);
        addParamsPanel(newParam);
    }
    
    //Updates the list of params and redraws them on screen
    public void refresh(){
       data.updateListofParams(PanelofParams);       
       loadUI();
    }
    
    
    // OTHER //
    
    public void refactorContainerReferenceInUI(String oldName, String newName){
        data.updateListofParams(PanelofParams); 
        data.refactorContainerReference(oldName, newName);
        saved.refactorContainerReference(oldName, newName);
        loadUI();
    }
    
    
    
    // GETTERS //
    
    //Gets the panel holding the params
    protected JPanel getPanelofParams(){
        return PanelofParams;
    }
    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ParamsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ParamsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ParamsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ParamsUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ParamsUI dialog = new ParamsUI(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton CreateButton;
    private javax.swing.JPanel PanelofParams;
    private javax.swing.JButton RemoveAllButton;
    private javax.swing.JScrollPane ScrollPaneOfParams;
    private javax.swing.JButton UpdateButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration//GEN-END:variables
}
