/*
 * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * ApplicationTypeOptionsPanel.java
 *
 * Created on Nov 3, 2008, 1:33:55 PM
 */
package org.graalvm.visualvm.modules.customtype.options;

import org.graalvm.visualvm.modules.customtype.ApplicationType;
import org.graalvm.visualvm.modules.customtype.ApplicationTypeManager;
import org.graalvm.visualvm.modules.customtype.ui.ApplicationTypeForm;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;

/**
 *
 * @author Jaroslav Bachorik
 */
public class ApplicationTypeOptionsPanel extends javax.swing.JPanel {

    private static class AppTypeTableMode extends AbstractTableModel {

        final private List<ApplicationType> types = new ArrayList<ApplicationType>();

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

        @Override
        public int getRowCount() {
            synchronized (types) {
                return types.size();
            }
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            synchronized (types) {
                switch (columnIndex) {
                    case 0: {
                        return types.get(rowIndex).getName();
                    }
                    case 1: {
                        return true;
                    }
                    default: {
                        return null;
                    }
                }
            }
        }

        ApplicationType getTypeAt(int selectedIndex) {
            synchronized (types) {
                return types.get(selectedIndex);
            }
        }

        void update() {
            synchronized (types) {
                types.clear();
                types.addAll(ApplicationTypeManager.getDefault().listTypes());
                fireTableDataChanged();
            }
        }
    }
    final private AppTypeTableMode tableModel = new AppTypeTableMode();

    /** Creates new form ApplicationTypeOptionsPanel */
    public ApplicationTypeOptionsPanel() {
        initComponents();
        appTypeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    menuEdit.setEnabled(appTypeTable.getSelectedRowCount() == 1);
                    menuDelete.setEnabled(appTypeTable.getSelectedRowCount() > 0);
                }
            }
        });
    }

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

        tablePopupMenu = new javax.swing.JPopupMenu();
        menuNew = new javax.swing.JMenuItem();
        menuEdit = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        menuDelete = new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        appTypeTable = new javax.swing.JTable();

        menuNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_INSERT, java.awt.event.InputEvent.CTRL_MASK));
        menuNew.setMnemonic('C');
        menuNew.setText(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.menuNew.text")); // NOI18N
        menuNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuNewActionPerformed(evt);
            }
        });
        tablePopupMenu.add(menuNew);

        menuEdit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, java.awt.event.InputEvent.CTRL_MASK));
        menuEdit.setMnemonic('E');
        menuEdit.setText(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.menuEdit.text")); // NOI18N
        menuEdit.setEnabled(false);
        menuEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editApplicationType(evt);
            }
        });
        tablePopupMenu.add(menuEdit);
        tablePopupMenu.add(jSeparator1);

        menuDelete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
        menuDelete.setMnemonic('D');
        menuDelete.setText(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.menuDelete.text")); // NOI18N
        menuDelete.setEnabled(false);
        menuDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteApptype(evt);
            }
        });
        tablePopupMenu.add(menuDelete);

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel1.setText(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.jLabel1.text")); // NOI18N

        appTypeTable.setAutoCreateRowSorter(true);
        appTypeTable.setModel(tableModel);
        appTypeTable.setComponentPopupMenu(tablePopupMenu);
        appTypeTable.setOpaque(false);
        appTypeTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(appTypeTable);
        appTypeTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        appTypeTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.appTypeTable.columnModel.title0")); // NOI18N
        appTypeTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(ApplicationTypeOptionsPanel.class, "ApplicationTypeOptionsPanel.appTypeTable.columnModel.title1")); // 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)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void editApplicationType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editApplicationType
        final ApplicationType at = tableModel.getTypeAt(appTypeTable.getSelectedRow());
        final ApplicationTypeForm form = new ApplicationTypeForm(at);

        final DialogDescriptor[] dd = new DialogDescriptor[1];

        dd[0] = new DialogDescriptor(form, "Application Type Details", true, new Object[]{form.getValidationSupport().getOkButton(), DialogDescriptor.CANCEL_OPTION}, form.getValidationSupport().getOkButton(), DialogDescriptor.DEFAULT_ALIGN, null, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == form.getValidationSupport().getOkButton() && form.storeData()) {
                    dd[0].setClosingOptions(new Object[]{form.getValidationSupport().getOkButton()});
                }
            }
        });

        dd[0].setClosingOptions(new Object[]{DialogDescriptor.CANCEL_OPTION});

        Dialog dlg = DialogDisplayer.getDefault().createDialog(dd[0]);
        dlg.setVisible(true);
        if (dd[0].getValue() == form.getValidationSupport().getOkButton()) {
            try {
                ApplicationTypeManager.getDefault().storeType(at);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_editApplicationType

    private void menuNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuNewActionPerformed
        ApplicationType eat = ApplicationTypeManager.getDefault().newType("");
        final ApplicationTypeForm form = new ApplicationTypeForm(eat);

        final DialogDescriptor[] dd = new DialogDescriptor[1];

        dd[0] = new DialogDescriptor(form, "New Application Type Details", true, new Object[]{form.getValidationSupport().getOkButton(), DialogDescriptor.CANCEL_OPTION}, form.getValidationSupport().getOkButton(), DialogDescriptor.DEFAULT_ALIGN, null, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().equals(form.getValidationSupport().getOkButton()) && form.storeData()) {
                    dd[0].setClosingOptions(new Object[]{form.getValidationSupport().getOkButton()});
                }
            }
        });

        dd[0].setClosingOptions(new Object[]{DialogDescriptor.CANCEL_OPTION});

        Dialog dlg = DialogDisplayer.getDefault().createDialog(dd[0]);
        dlg.setVisible(true);
        if (dd[0].getValue() == form.getValidationSupport().getOkButton()) {
            try {
                ApplicationTypeManager.getDefault().storeType(eat);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        tableModel.update();
    }//GEN-LAST:event_menuNewActionPerformed

    private void deleteApptype(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteApptype
        final ApplicationType at = tableModel.getTypeAt(appTypeTable.getSelectedRow());
        ApplicationTypeManager.getDefault().removeType(at);
        tableModel.update();
    }//GEN-LAST:event_deleteApptype

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable appTypeTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuItem menuDelete;
    private javax.swing.JMenuItem menuEdit;
    private javax.swing.JMenuItem menuNew;
    private javax.swing.JPopupMenu tablePopupMenu;
    // End of variables declaration//GEN-END:variables

    void load() {
        tableModel.update();
    }

    void store() {
        System.err.println("Store");
    }
}
