 /*
 *
 * Autopsy Forensic Browser
 * 
 * Copyright 2012 Basis Technology Corp.
 * 
 * Copyright 2012 42six Solutions.
 * Contact: aebadirad <at> 42six <dot> com
 * Project Contact/Architect: carrier <at> sleuthkit <dot> org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sleuthkit.autopsy.report;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.FileUtil;
import org.sleuthkit.autopsy.coreutils.Logger;

public class ReportPanel extends javax.swing.JPanel {

    private ReportPanelAction rpa;
    private static final Logger logger = Logger.getLogger(ReportPanel.class.getName());

    /**
     * Creates new form ReportPanel
     */
    public ReportPanel(ReportPanelAction reportPanelAction) {
        initComponents();
        rpa = reportPanelAction;
    }

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

        reportScrollPane = new javax.swing.JScrollPane();
        reportSummaryPanel = new javax.swing.JPanel();
        closeButton = new javax.swing.JButton();
        exportButton = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();
        LABEL_LOC = new javax.swing.JLabel();
        ButtonOpenFolder = new javax.swing.JButton();

        reportScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.reportScrollPane.border.title"))); // NOI18N

        javax.swing.GroupLayout reportSummaryPanelLayout = new javax.swing.GroupLayout(reportSummaryPanel);
        reportSummaryPanel.setLayout(reportSummaryPanelLayout);
        reportSummaryPanelLayout.setHorizontalGroup(
            reportSummaryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 675, Short.MAX_VALUE)
        );
        reportSummaryPanelLayout.setVerticalGroup(
            reportSummaryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 214, Short.MAX_VALUE)
        );

        reportScrollPane.setViewportView(reportSummaryPanel);

        org.openide.awt.Mnemonics.setLocalizedText(closeButton, org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.closeButton.text_1")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(exportButton, org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.exportButton.text")); // NOI18N
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(statusLabel, org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.statusLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(LABEL_LOC, org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.LABEL_LOC.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(ButtonOpenFolder, org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.ButtonOpenFolder.text_1")); // NOI18N
        ButtonOpenFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonOpenFolderActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(reportScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                    .addComponent(statusLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(LABEL_LOC)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(exportButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ButtonOpenFolder)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(closeButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(reportScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(statusLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(LABEL_LOC)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(exportButton)
                    .addComponent(ButtonOpenFolder))
                .addGap(8, 8, 8))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
        HashMap<ReportModule, String> reports = rpa.getReports();
        exportReportAction(reports);
    }//GEN-LAST:event_exportButtonActionPerformed

    private void ButtonOpenFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonOpenFolderActionPerformed
        String path = Case.getCurrentCase().getCaseDirectory() + File.separator + "Reports";
        File dir = new File(path);
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().open(dir);
            } catch (IOException ioe) {
                logger.log(Level.WARNING, "Could not open folder [" + path + "]", ioe);
            }
        }
    }//GEN-LAST:event_ButtonOpenFolderActionPerformed

    public void setCloseButtonActionListener(ActionListener e) {
        closeButton.addActionListener(e);
    }

    public void setFinishedReportText() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String reportText = "These reports were generated on " + dateFormat.format(new Date()) + ".";
        String loc = "Reports extracted to: " + Case.getCurrentCase().getCaseDirectory() + File.separator + "Reports";
        statusLabel.setText(reportText);
        LABEL_LOC.setText(loc);
        
        final JPanel tempPanel = new JPanel(new GridBagLayout());
        //tempPanel.setMinimumSize(new Dimension(540,240));
        SwingUtilities.invokeLater(new Runnable() {

            GridBagConstraints c = new GridBagConstraints();

            @Override
            public void run() {
                HashMap<ReportModule, String> reports = rpa.getReports();
                int cc = 0;
                for (Map.Entry<ReportModule, String> entry : reports.entrySet()) {
                    c.fill = GridBagConstraints.HORIZONTAL;
                    c.weightx = 1;
                    c.gridwidth = 1;
                    c.gridx = 0;
                    c.gridy = cc;
                    c.insets = new Insets(0, 0, 0, 0); // remove padding
                    String info = entry.getKey().getName() + " report";
                    JLabel infoLabel = new JLabel(info);
                    tempPanel.add(infoLabel, c);
                    
                    c.fill = GridBagConstraints.BASELINE_TRAILING;
                    c.weightx = 0.0;
                    c.gridwidth = 1;
                    c.gridheight = 1;
                    c.gridx = 1;
                    c.gridy = cc;
                    JButton viewButton = new JButton("View Report");
                    final ReportModule rep = entry.getKey();
                    final String path = entry.getValue();
                    viewButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            rep.getPreview(path);
                        }
                    });
                    tempPanel.add(viewButton, c);
                    
                    c.fill = GridBagConstraints.HORIZONTAL;
                    c.weightx = 1;
                    c.gridwidth = 3;
                    c.gridheight = 1;
                    c.gridx = 0;
                    c.gridy = ++cc;
                    c.insets = new Insets(0, 0, 15, 0); // row padding
                    tempPanel.revalidate();
                    tempPanel.repaint();
                    cc++;
                }
            }
        });
        reportSummaryPanel.setLayout(new GridLayout(0, 1));
        reportSummaryPanel.add(tempPanel, 0);
        //reportScrollPane.revalidate();
        //reportScrollPane.repaint();
        
    }
    
    private void exportReportAction(HashMap<ReportModule, String> reports) {
        JFileChooser exportChooser = new JFileChooser();
        int option = exportChooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            if (exportChooser.getSelectedFile() != null) {
                File file = exportChooser.getSelectedFile();
                String path = file.getParent();
                String name = file.getName();
                for (Map.Entry<ReportModule, String> entry : reports.entrySet()) {
                    exportReport(path, name, entry);
                }
            }
        }
    }

    private void exportReport(String path, String name, Map.Entry<ReportModule, String> entry) {
        ReportModule report = entry.getKey();
        String ext = report.getExtension();
        String original = entry.getValue();
        try {
            if(report.getName().equals("HTML")) {
                String newpath = FileUtil.copyFolder(original.substring(0, original.lastIndexOf("\\")), path, name);
                JOptionPane.showMessageDialog(this, "\n" + report.getName() + " report has been successfully saved to: \n" + newpath);
            } else {
                String newpath = FileUtil.copyFile(original, path, name + "-" + report.getName(), ext, true);
                JOptionPane.showMessageDialog(this, "\n" + report.getName() + " report has been successfully saved to: \n" + newpath);
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "\n" + report.getName() + " report has failed to save! \n Reason: " + ex);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonOpenFolder;
    private javax.swing.JLabel LABEL_LOC;
    private javax.swing.JButton closeButton;
    private javax.swing.JButton exportButton;
    private javax.swing.JScrollPane reportScrollPane;
    private javax.swing.JPanel reportSummaryPanel;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration//GEN-END:variables
}
