/*
 * Copyright (C) 2009-2017 Alistair Neil <info@dazzleships.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package client;

import java.awt.event.MouseEvent;
import javax.swing.event.TableModelEvent;
import lib.GTKFixes;
import lib.Localisation;
import lib.Utilities;

/**
 *
 * @author Alistair Neil <info@dazzleships.net>
 */
public class GuardNodeDialog extends javax.swing.JDialog {

    public static final int CANCEL = 0;
    public static final int APPLY = 1;
    public static final int RESET = 2;
    private static final String ATLAS = "https://atlas.torproject.org/";
    private static final Localisation LOCAL = new Localisation("resources/MessagesBundle");
    private int intRowSelected = -1;
    private int returnStatus = CANCEL;
    private final GuardNodeTableModel gntm;
    private NodeList nl;

    /**
     * Creates new form GuardNodeDialog
     *
     * @param parent
     * @param modal
     */
    public GuardNodeDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        GTKFixes.fixTextAreaColor(jTextArea1);
        jTableGuards.setComponentPopupMenu(popupTable);
        gntm = new GuardNodeTableModel();
        gntm.setColumnName(LOCAL.getString("guardtable_col1"), 0);
        gntm.setColumnName(LOCAL.getString("guardtable_col2"), 1);
        gntm.setColumnName(LOCAL.getString("guardtable_col3"), 2);
        gntm.setColumnName(LOCAL.getString("guardtable_col4"), 3);
        gntm.addTableModelListener(new javax.swing.event.TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                if (gntm.getEnabledCount() >= 3 || gntm.getEnabledCount() == 0) {
                    jButtonApply.setEnabled(true);
                } else {
                    jButtonApply.setEnabled(false);
                }
            }
        });

        jTableGuards.setModel(gntm);
        adjustGuardTableColumns();
    }

    /**
     * Set the nodelist
     *
     * @param nl
     */
    public void setNodeList(NodeList nl) {
        this.nl = nl;
        this.nl.setGuardNodeTableModel(gntm);
        this.nl.refreshGuardTableModel();
        adjustGuardTableColumns();
    }

    /**
     * Adjust guard table column widths
     */
    private void adjustGuardTableColumns() {
        // Adjust table column widths
        Utilities.adjustTableColumnWidth(jTableGuards,
                "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "XXXXXXXXXXXXXXX",
                "XXXXXXXXXXXXXXX");
    }

    private void clearSelections() {

        for (int row = 0; row < jTableGuards.getRowCount(); row++) {
            jTableGuards.setValueAt(false, row, 3);
        }
    }

    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    /**
     * @return the return status of this dialog - one of RET_OK or RET_CANCEL
     */
    public int getReturnStatus() {
        return returnStatus;
    }

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

        popupTable = new javax.swing.JPopupMenu();
        jMenuNodeDetails = new javax.swing.JMenuItem();
        jMenuWhois = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableGuards = new javax.swing.JTable();
        jButtonClear = new javax.swing.JButton();
        jButtonApply = new javax.swing.JButton();
        jButtonClose = new javax.swing.JButton();
        jTextArea1 = new javax.swing.JTextArea();

        popupTable.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                popupTablePopupMenuWillBecomeVisible(evt);
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        jMenuNodeDetails.setText(LOCAL.getString("table_popup_details")); // NOI18N
        jMenuNodeDetails.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuNodeDetailsActionPerformed(evt);
            }
        });
        popupTable.add(jMenuNodeDetails);

        jMenuWhois.setText(LOCAL.getString("table_popup_whois")); // NOI18N
        jMenuWhois.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuWhoisActionPerformed(evt);
            }
        });
        popupTable.add(jMenuWhois);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(LOCAL.getString("wintitle_guardnodes")); // NOI18N
        setResizable(false);

        jTableGuards.setAutoCreateRowSorter(true);
        jTableGuards.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableGuards.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableGuardsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableGuards);

        jButtonClear.setText(LOCAL.getString("button_clearguards")); // NOI18N
        jButtonClear.setToolTipText(LOCAL.getString("ttip_clearguards")); // NOI18N
        jButtonClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClearActionPerformed(evt);
            }
        });

        jButtonApply.setText(LOCAL.getString("button_apply")); // NOI18N
        jButtonApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonApplyActionPerformed(evt);
            }
        });

        jButtonClose.setText(LOCAL.getString("button_close")); // NOI18N
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(40);
        jTextArea1.setFont(new javax.swing.JLabel().getFont());
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(2);
        jTextArea1.setText(LOCAL.getString("label_guard_minimum")); // NOI18N
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setDisabledTextColor(jTextArea1.getForeground());
        jTextArea1.setEnabled(false);
        jTextArea1.setMinimumSize(new java.awt.Dimension(0, 0));
        jTextArea1.setOpaque(false);
        jTextArea1.setRequestFocusEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().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()
                        .addComponent(jButtonClear)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonClose)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonApply))
                    .addComponent(jTextArea1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextArea1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonClear)
                    .addComponent(jButtonApply)
                    .addComponent(jButtonClose))
                .addContainerGap())
        );

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

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
        doClose(CANCEL);
    }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jButtonApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonApplyActionPerformed
        nl.saveGuardWhitelist();
        doClose(APPLY);
    }//GEN-LAST:event_jButtonApplyActionPerformed

    private void jButtonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClearActionPerformed
        clearSelections();
    }//GEN-LAST:event_jButtonClearActionPerformed

    private void jMenuNodeDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuNodeDetailsActionPerformed
        String finger = (String) gntm.getValueAt(intRowSelected, 4);
        finger = finger.replace("$", "");
        Utilities.openFileExternally(ATLAS + "#details/" + finger);
    }//GEN-LAST:event_jMenuNodeDetailsActionPerformed

    private void jMenuWhoisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuWhoisActionPerformed
        String finger = (String) gntm.getValueAt(intRowSelected, 4);
        NodeItem ni = nl.getNode(finger);
        if (ni != null) {
            Utilities.openFileExternally("https://www.networksolutions.com/whois/results.jsp?ip=" + ni.getIPAddress());
        }
    }//GEN-LAST:event_jMenuWhoisActionPerformed

    private void popupTablePopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popupTablePopupMenuWillBecomeVisible
        jMenuWhois.setEnabled(intRowSelected > -1);
        jMenuNodeDetails.setEnabled(intRowSelected > -1);
    }//GEN-LAST:event_popupTablePopupMenuWillBecomeVisible

    private void jTableGuardsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableGuardsMouseClicked
        if (evt.getButton() != MouseEvent.BUTTON1) {
            return;
        }
        intRowSelected = jTableGuards.getSelectedRow();
        if (intRowSelected > 0) {
            intRowSelected = jTableGuards.convertRowIndexToModel(intRowSelected);
        }
    }//GEN-LAST:event_jTableGuardsMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonApply;
    private javax.swing.JButton jButtonClear;
    private javax.swing.JButton jButtonClose;
    private javax.swing.JMenuItem jMenuNodeDetails;
    private javax.swing.JMenuItem jMenuWhois;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableGuards;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JPopupMenu popupTable;
    // End of variables declaration//GEN-END:variables
}
