/*
 * Autopsy Forensic Browser
 * 
 * Copyright 2011 Basis Technology Corp.
 * Contact: 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.
 */

/*
 * HashDbSimplePanel.java
 *
 * Created on May 7, 2012, 10:38:26 AM
 */
package org.sleuthkit.autopsy.hashdatabase;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import org.sleuthkit.autopsy.ingest.IngestManager;

/**
 *
 * @author dfickling
 */
public class HashDbSimplePanel extends javax.swing.JPanel {
    
    private static final Logger logger = Logger.getLogger(HashDbSimplePanel.class.getName());
    private HashTableModel knownBadTableModel;
    private HashDb nsrl;

    /** Creates new form HashDbSimplePanel */
    public HashDbSimplePanel() {
        knownBadTableModel = new HashTableModel();
        initComponents();
        customizeComponents();
    }
    
    private void reloadCalc() {
        final HashDbXML xmlHandle = HashDbXML.getCurrent();
        final HashDb nsrlDb = xmlHandle.getNSRLSet();
        final boolean nsrlUsed = 
                nsrlDb != null 
                && nsrlDb.getUseForIngest()== true
                && nsrlDb.indexExists();
        final List<HashDb> knowns = xmlHandle.getKnownBadSets();
        final boolean knownExists = !knowns.isEmpty();
        boolean knownUsed = false;
        if (knownExists) {
            for (HashDb known : knowns) {
                if (known.getUseForIngest() == true) {
                    knownUsed = true;
                    break;
                }
            }
        }
        
        if(! nsrlUsed
                && ! knownUsed ) {
            calcHashesButton.setEnabled(true);
            calcHashesButton.setSelected(true);
            xmlHandle.setCalculate(true);
        } else {
            calcHashesButton.setEnabled(false);
            calcHashesButton.setSelected(false);
            xmlHandle.setCalculate(false);
        }
    }
    
    private void customizeComponents() {
        final HashDbXML xmlHandle = HashDbXML.getCurrent();
        calcHashesButton.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(calcHashesButton.isSelected()) {
                    xmlHandle.setCalculate(true);
                } else {
                    xmlHandle.setCalculate(false);
                }
            }
            
        });
        
        notableHashTable.setModel(knownBadTableModel);
        
        notableHashTable.setTableHeader(null);
        notableHashTable.setRowSelectionAllowed(false);
        //customize column witdhs
        final int width1 = jScrollPane1.getPreferredSize().width;
        notableHashTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
        TableColumn column1 = null;
        for (int i = 0; i < notableHashTable.getColumnCount(); i++) {
            column1 = notableHashTable.getColumnModel().getColumn(i);
            if (i == 0) {
                column1.setPreferredWidth(((int) (width1 * 0.07)));
            } else {
                column1.setPreferredWidth(((int) (width1 * 0.92)));
            }
        }
        
        reloadSets();
    }

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

        jScrollPane1 = new javax.swing.JScrollPane();
        notableHashTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        nsrlDbLabel = new javax.swing.JLabel();
        calcHashesButton = new javax.swing.JCheckBox();
        nsrlDbLabelVal = new javax.swing.JLabel();

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        notableHashTable.setBackground(new java.awt.Color(240, 240, 240));
        notableHashTable.setShowHorizontalLines(false);
        notableHashTable.setShowVerticalLines(false);
        jScrollPane1.setViewportView(notableHashTable);

        jLabel1.setText(org.openide.util.NbBundle.getMessage(HashDbSimplePanel.class, "HashDbSimplePanel.jLabel1.text")); // NOI18N

        nsrlDbLabel.setText(org.openide.util.NbBundle.getMessage(HashDbSimplePanel.class, "HashDbSimplePanel.nsrlDbLabel.text")); // NOI18N

        calcHashesButton.setText(org.openide.util.NbBundle.getMessage(HashDbSimplePanel.class, "HashDbSimplePanel.calcHashesButton.text")); // NOI18N

        nsrlDbLabelVal.setText(org.openide.util.NbBundle.getMessage(HashDbSimplePanel.class, "HashDbSimplePanel.nsrlDbLabelVal.text")); // NOI18N

        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)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(nsrlDbLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(nsrlDbLabelVal, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(calcHashesButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nsrlDbLabel)
                    .addComponent(nsrlDbLabelVal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(calcHashesButton)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox calcHashesButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable notableHashTable;
    private javax.swing.JLabel nsrlDbLabel;
    private javax.swing.JLabel nsrlDbLabelVal;
    // End of variables declaration//GEN-END:variables

    private void reloadSets() {
        nsrl = HashDbXML.getCurrent().getNSRLSet();

        if (nsrl == null || nsrl.getUseForIngest() == false) {
            nsrlDbLabelVal.setText("Disabled");
        }
        else if (nsrl.indexExists() == false) {
            nsrlDbLabelVal.setText("Disabled (No index)");
        }
        else {
            nsrlDbLabelVal.setText("Enabled");
        }
        
        reloadCalc();
        
        knownBadTableModel.resync();
    }
    
   

    private class HashTableModel extends AbstractTableModel {
        
        private HashDbXML xmlHandle = HashDbXML.getCurrent();
        
        private void resync() {
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            int size = xmlHandle.getKnownBadSets().size();
            return size == 0 ? 1 : size;
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (xmlHandle.getKnownBadSets().isEmpty()) {
                if (columnIndex == 0) {
                    return "";
                } else {
                    return "Disabled";
                }
            } else {
                HashDb db = xmlHandle.getKnownBadSets().get(rowIndex);
                if (columnIndex == 0) {
                    return db.getUseForIngest();
                } else {
                    return db.getName();
                }
            }
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return !IngestManager.getDefault().isIngestRunning() && columnIndex == 0;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if(columnIndex == 0){
                HashDb db = xmlHandle.getKnownBadSets().get(rowIndex);
                if(((Boolean) getValueAt(rowIndex, columnIndex)) || IndexStatus.isIngestible(db.status())) {
                        db.setUseForIngest((Boolean) aValue);
                } else {
                        JOptionPane.showMessageDialog(HashDbSimplePanel.this, "Databases must be indexed before they can be used for ingest");
                }
                reloadSets();
            }
        }
        
        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
        
    }
}
