/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package scriptbuilder.gui;

import java.awt.GridLayout;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import scriptbuilder.gui.panels.IncidentPaletteAddPanel;
import scriptbuilder.structures.*;

/**
 *
 * @author Bryan McGuffin
 */
public class IncidentPaletteFrame extends javax.swing.JFrame
{
    
    private String incDir;

    private SimulationScript script;

    private ScriptBuilderFrame parent;

    private SimulationScript dummyScript;

    /**
     * The list of incidents to be displayed in the palette.
     */
    public ArrayList<ScriptIncident> incidentList;

    JPanel panelAdd;

    /**
     * Create new IncidentPaletteFrame from the form.
     *
     * @param scr The currently running script, to which new incidents will be
     * added.
     */
    public IncidentPaletteFrame(SimulationScript scr, ScriptBuilderFrame frame)
    {
        script = scr;

        parent = frame;

        panelAdd = new JPanel();

        dummyScript = new SimulationScript();

        incidentList = new ArrayList<ScriptIncident>();

        panelAdd.setLayout(new GridLayout(0, 1));

        initComponents();

        String propfilename = "/scriptbuilder/gui/application.properties";
        String propKey = "Incidents.directory";
        incDir = "";
        // Load the application properties (created by build.xml)
        try
        {
            Properties props = new Properties();
            props.load(this.getClass().getResourceAsStream(propfilename));
            incDir = (String) props.get(propKey);
        }
        catch (IOException ex)
        {
            Logger.getLogger("scriptbuilder.gui").log(Level.SEVERE,
                    "IncidentPaletteFrame.loadIncidentsFromFiles."
                    + " IOError reading " + propfilename);
        }

        incidentList = loadIncidentsFromFiles(incDir);

        refresh();

    }

    private ArrayList<ScriptIncident> loadIncidentsFromFiles(String directoryName)
    {

        ArrayList<ScriptIncident> newList = new ArrayList<ScriptIncident>();
        File folder = new File(directoryName);

        File[] incidentFiles;

        ExtensionFileFilter filter = new ExtensionFileFilter("Script Incident (.xml)", new String[]
        {
            "xml"
        });

        //If the folder isn't correct then just hand back an empty list
        if (!folder.exists())
        {
            JOptionPane.showMessageDialog(this, 
                    "Unable to locate folder of existing incidents.\n"
                  + "Folder \""+incDir+"\" should have been included in the\n"
                  + "ScriptBuilder.zip file you downloaded.\n"
                  + "TO FIX: Close the ScriptBuilder program and run it from\n"
                  + "the same directory where you opened the .zip file.\n\n"
                  + "(If the problem persists, contact the developers.)", "Missing Folder: \""+incDir+"\"", JOptionPane.ERROR_MESSAGE);
            return newList;
        }
        
        incidentFiles = folder.listFiles();

        for (File file : incidentFiles)
        {
            if (filter.accept(file))
            {
                dummyScript = new SimulationScript();
                dummyScript.loadScriptFromFile(file);

                newList.add(dummyScript.incidents.get(0));
            }
        }

        return newList;
    }

    private ArrayList<ScriptIncident> filterIncidentsInScript(ArrayList<ScriptIncident> list)
    {
        ArrayList<ScriptIncident> newList = new ArrayList<ScriptIncident>();

        for (ScriptIncident inc : list)
        {
            if (!scriptContainsLogNum(script, inc.number))
            {
                newList.add(inc);
            }
        }

        return newList;
    }

    private boolean scriptContainsLogNum(SimulationScript script, int num)
    {
        for (ScriptIncident incident : script.incidents)
        {
            if (incident != null && incident.number == num)
            {
                return true;
            }
        }

        return false;
    }

    private void loadPanels(ArrayList<ScriptIncident> incList)
    {
        scrollAddPanels.setViewport(new JViewport());
        panelAdd.removeAll();
        labelFileCount.setText("Found " + incList.size() + " available incidents.");
        for (ScriptIncident inc : incList)
        {

            panelAdd.add(new IncidentPaletteAddPanel(inc, this));
        }
        scrollAddPanels.getViewport().add(panelAdd);
    }

    private void refresh()
    {

        incidentList = filterIncidentsInScript(incidentList);
        loadPanels(incidentList);
        getCurrentlyLoadedIncidents();
    }

    /**
     * Attempt to add an incident to the script. If successful, refresh the
     * palette.
     *
     * @param incPanel the Add Panel which holds the incident to be added.
     */
    public void addIncidentToScript(IncidentPaletteAddPanel incPanel)
    {
        if (script.addIncident(incPanel.incident))
        {
            refresh();
        }
    }

    private void getCurrentlyLoadedIncidents()
    {
        tableCurrentIncidents.removeAll();
        int currentRow = 0;
        for (ScriptIncident inc : script.incidents)
        {
            if (inc != null)
            {
                SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                df.setTimeZone(TimeZone.getTimeZone("GMT"));
                String incStart = df.format(new Date(inc.offset * 1000));
                tableCurrentIncidents.getModel().setValueAt(inc.number, currentRow, 0);
                tableCurrentIncidents.getModel().setValueAt(incStart, currentRow, 1);
                tableCurrentIncidents.getModel().setValueAt(inc.name, currentRow, 2);
                currentRow++;
            }
        }
        labelIncidentCount.setText(currentRow + " incidents currently in script.");
    }

    /**
     * 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()
    {

        jPanel1 = new javax.swing.JPanel();
        btnCreateIncident = new javax.swing.JButton();
        txtSearchFilter = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableCurrentIncidents = new javax.swing.JTable();
        labelIncidentCount = new javax.swing.JLabel();
        scrollAddPanels = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();
        btnClosePalette = new javax.swing.JButton();
        labelFileCount = new javax.swing.JLabel();

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

        txtSearchFilter.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                txtSearchFilterActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtSearchFilter)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCreateIncident, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSearchFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCreateIncident))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tableCurrentIncidents.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String []
            {
                "Incident #", "Start Time", "Title"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean []
            {
                false, false, false
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex)
            {
                return canEdit [columnIndex];
            }
        });
        tableCurrentIncidents.setToolTipText("");
        tableCurrentIncidents.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tableCurrentIncidents);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelIncidentCount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(labelIncidentCount, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        scrollAddPanels.setMaximumSize(new java.awt.Dimension(99999, 99999));
        scrollAddPanels.setMinimumSize(new java.awt.Dimension(566, 387));
        scrollAddPanels.setPreferredSize(new java.awt.Dimension(566, 387));

        btnClosePalette.setText("Done");
        btnClosePalette.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnClosePaletteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelFileCount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClosePalette)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnClosePalette)
                .addComponent(labelFileCount))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollAddPanels, javax.swing.GroupLayout.DEFAULT_SIZE, 687, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollAddPanels, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

    private void btnCreateIncidentActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnCreateIncidentActionPerformed
    {//GEN-HEADEREND:event_btnCreateIncidentActionPerformed
        int newLogNum = 100;
        boolean found = false;
        while (!found)
        {
            newLogNum++;
            if (!scriptContainsLogNum(script, newLogNum))
            {
                found = true;
                for (ScriptIncident incident : incidentList)
                {
                    if (incident.number == newLogNum)
                    {
                        found = false;
                    }
                }
            }
        }

        ScriptIncident newInc = new ScriptIncident(newLogNum, "New Incident", LocalDate.now().toString(), script);
        if (script.addIncident(newInc))
        {
            new IncidentEditorFrame(newInc, parent).setVisible(true);
            this.dispose();
        }

    }//GEN-LAST:event_btnCreateIncidentActionPerformed

    private void btnClosePaletteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnClosePaletteActionPerformed
    {//GEN-HEADEREND:event_btnClosePaletteActionPerformed
        script.update();
        parent.update(script, script);
        parent.repaint();
        this.dispose();
    }//GEN-LAST:event_btnClosePaletteActionPerformed

    private void txtSearchFilterActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_txtSearchFilterActionPerformed
    {//GEN-HEADEREND:event_txtSearchFilterActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSearchFilterActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClosePalette;
    private javax.swing.JButton btnCreateIncident;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelFileCount;
    private javax.swing.JLabel labelIncidentCount;
    private javax.swing.JScrollPane scrollAddPanels;
    private javax.swing.JTable tableCurrentIncidents;
    private javax.swing.JTextField txtSearchFilter;
    // End of variables declaration//GEN-END:variables

}
