/*
 * Copyright (C) 2014 Laboratoire ThéMA - UMR 6049 - CNRS / Université de Franche-Comté
 * http://thema.univ-fcomte.fr
 *
 * 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 3 of the License, or
 * 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, see <http://www.gnu.org/licenses/>.
 */


package org.thema.graphab.model;

import java.awt.Component;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.geotools.coverage.grid.GridCoverage2D;
import org.thema.common.Config;
import org.thema.common.ProgressBar;
import org.thema.common.Util;
import org.thema.data.IOImage;
import org.thema.drawshape.layer.DefaultGroupLayer;
import org.thema.drawshape.layer.RasterLayer;
import org.thema.graphab.Project;
import org.thema.graphab.links.Linkset;
import org.thema.graphab.util.RSTGridReader;

/**
 * Extrapolate a presence probability from a distribution model to the whole area.
 * 
 * @author Gilles Vuidel
 */
public class ExtrapolateDialog extends javax.swing.JDialog {

    private static class DecimalFormatRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            value = String.valueOf(((Number)value).doubleValue());
            return super.getTableCellRendererComponent(
                table, value, isSelected, hasFocus, row, column );
        }
    }

    private Project project;
    private LinkedHashMap<String, GridCoverage2D> extVars;
    private DefaultGroupLayer layers;

    /**
     * Creates a new ExtrapolateDialog form 
     * @param owner the parent frame
     * @param project the current project
     * @param linkset the linkset for cost distance
     * @param d the distance associated with p
     * @param p th probability associated with d
     * @param vars the variables of the model
     * @param coefs the variable coefficients of the model 
     * @param extVars the external variables (other rasters)
     * @param multiAttach is multi patch attachment ?
     * @param dMax the max distance for multi attachment
     */
    public ExtrapolateDialog(Frame owner, Project project, Linkset linkset, double d, double p, List<String> vars, double[] coefs,
            LinkedHashMap<String, GridCoverage2D> extVars, boolean multiAttach, double dMax) {
        super(owner, true);

        initComponents();
        setLocationRelativeTo(owner);
        getRootPane().setDefaultButton(okButton);

        table.getColumnModel().getColumn(1).setCellRenderer(new DecimalFormatRenderer());
        
        this.project = project;
        costComboBox.setModel(new DefaultComboBoxModel(project.getLinksets().toArray()));
        resolSpinner.setValue(project.getResolution()*10);
        
        if(linkset != null) {
            costComboBox.setSelectedItem(linkset);
            this.extVars = extVars;
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setValueAt(coefs[0], 0, 1);
            for(int i = 1; i < coefs.length; i++) {
                model.addRow(new Object[] {vars.get(i-1), coefs[i]});
            }

            dSpinner.setValue(d);
            pSpinner.setValue(p);
            multiAttachCheckBox.setSelected(multiAttach);
            dMaxSpinner.setValue(dMax);
        } else {
            this.extVars = new LinkedHashMap<>();
        }

    }

    /** 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() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        pSpinner = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        alphaTextField = new javax.swing.JTextField();
        dSpinner = new javax.swing.JSpinner();
        multiAttachCheckBox = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        dMaxSpinner = new javax.swing.JSpinner();
        costComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        addExtButton = new javax.swing.JButton();
        remVarButton = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        resolSpinner = new javax.swing.JSpinner();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        addPatchButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/thema/graphab/Bundle"); // NOI18N
        setTitle(bundle.getString("ExtrapolateDialog.title")); // NOI18N

        java.util.ResourceBundle bundle1 = java.util.ResourceBundle.getBundle("org/thema/graphab/model/Bundle"); // NOI18N
        okButton.setText(bundle1.getString("ExtrapolateDialog.okButton.text")); // NOI18N
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText(bundle1.getString("ExtrapolateDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle1.getString("ExtrapolateDialog.jPanel1.border.title"))); // NOI18N

        pSpinner.setModel(new javax.swing.SpinnerNumberModel(0.05d, 0.0d, 1.0d, 0.1d));
        pSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                pSpinnerStateChanged(evt);
            }
        });

        jLabel7.setText(bundle1.getString("ExtrapolateDialog.jLabel7.text")); // NOI18N

        jLabel6.setText(bundle1.getString("ExtrapolateDialog.jLabel6.text")); // NOI18N

        jLabel5.setText(bundle1.getString("ExtrapolateDialog.jLabel5.text")); // NOI18N

        jLabel8.setText(bundle1.getString("ExtrapolateDialog.jLabel8.text")); // NOI18N

        alphaTextField.setText(bundle1.getString("ExtrapolateDialog.alphaTextField.text")); // NOI18N

        dSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(1000.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));
        dSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                dSpinnerStateChanged(evt);
            }
        });

        multiAttachCheckBox.setText(bundle1.getString("ExtrapolateDialog.multiAttachCheckBox.text")); // NOI18N

        jLabel3.setText(bundle1.getString("ExtrapolateDialog.jLabel3.text")); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, multiAttachCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), jLabel3, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        dMaxSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(1000.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, multiAttachCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), dMaxSpinner, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(12, 12, 12)
                                .add(jLabel6)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(dSpinner))
                            .add(multiAttachCheckBox))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel7))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(dMaxSpinner)
                            .add(pSpinner, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                        .addContainerGap())
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel5)
                        .add(24, 24, 24)
                        .add(alphaTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
                        .add(36, 36, 36)
                        .add(jLabel8)
                        .add(30, 30, 30))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(6, 6, 6)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(alphaTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(dSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel7)
                    .add(pSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(multiAttachCheckBox)
                    .add(jLabel3)
                    .add(dMaxSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setText(bundle1.getString("ExtrapolateDialog.jLabel1.text")); // NOI18N

        jLabel2.setText(bundle1.getString("ExtrapolateDialog.jLabel2.text")); // NOI18N

        addExtButton.setText(bundle1.getString("ExtrapolateDialog.addExtButton.text")); // NOI18N
        addExtButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addExtButtonActionPerformed(evt);
            }
        });

        remVarButton.setText(bundle1.getString("ExtrapolateDialog.remVarButton.text")); // NOI18N
        remVarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                remVarButtonActionPerformed(evt);
            }
        });

        jLabel10.setText(bundle1.getString("ExtrapolateDialog.jLabel10.text")); // NOI18N

        resolSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(1.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Constant",  new Double(0.0)}
            },
            new String [] {
                "Variable", "Coef"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

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

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table);

        addPatchButton.setText(bundle1.getString("ExtrapolateDialog.addPatchButton.text")); // NOI18N
        addPatchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPatchButtonActionPerformed(evt);
            }
        });

        jLabel4.setText(bundle1.getString("ExtrapolateDialog.jLabel4.text")); // NOI18N

        nameTextField.setText(bundle1.getString("ExtrapolateDialog.nameTextField.text")); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel1)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(costComboBox, 0, 330, Short.MAX_VALUE))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(addPatchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(addExtButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(remVarButton))
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel10)
                                    .add(jLabel4))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                        .add(nameTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(okButton)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(cancelButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(resolSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 74, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(costComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(remVarButton)
                    .add(addExtButton)
                    .add(addPatchButton))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(resolSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel10))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(nameTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(cancelButton)
                    .add(okButton))
                .addContainerGap())
        );

        bindingGroup.bind();

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

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        new Thread(new Runnable() {
            @Override
            public void run() {
                TableModel model = table.getModel();
                double [] coefs = new double[model.getRowCount()];
                List<String> vars = new ArrayList<>();
                coefs[0] = (Double)model.getValueAt(0, 1);
                for(int i = 1; i < model.getRowCount(); i++) {
                    vars.add(model.getValueAt(i, 0).toString());
                    coefs[i] = (Double)model.getValueAt(i, 1);
                }
                ProgressBar monitor = Config.getProgressBar("Loading data...");
                RasterLayer l = DistribModel.extrapolate(project, (Double)resolSpinner.getValue(), vars, coefs,
                        Double.parseDouble(alphaTextField.getText()), extVars, (Linkset)costComboBox.getSelectedItem(),
                        multiAttachCheckBox.isSelected(), (Double)dMaxSpinner.getValue(), monitor);
                if(l == null) {
                    return;
                }
                l.setName(nameTextField.getText());
                if(layers == null) {
                    layers = new DefaultGroupLayer("Extrapolate");
                    project.addLayer(layers);
                }
                l.setRemovable(true);
                layers.addLayerFirst(l);
                
                try {
                    l.saveRaster(new File(project.getDirectory(), l.getName() + ".tif"));
                } catch (IOException ex) {
                    Logger.getLogger(ModelDialog.class.getName()).log(Level.SEVERE, null, ex);
                    JOptionPane.showMessageDialog(ExtrapolateDialog.this, "An error occured : \n" + ex.getLocalizedMessage());
                } finally {
                    monitor.close();
                }
            }
        }).start();

    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void pSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pSpinnerStateChanged
        alphaTextField.setText(String.valueOf(-Math.log((Double)pSpinner.getValue()) / (Double)dSpinner.getValue()));
}//GEN-LAST:event_pSpinnerStateChanged

    private void dSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_dSpinnerStateChanged
        alphaTextField.setText(String.valueOf(-Math.log((Double)pSpinner.getValue()) / (Double)dSpinner.getValue()));
}//GEN-LAST:event_dSpinnerStateChanged

    private void addExtButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addExtButtonActionPerformed
        File f = Util.getFile(".tif|.rst", "Raster image");
        if (f == null) {
            return;
        }
        try {
            GridCoverage2D coverage;
            if (f.getName().toLowerCase().endsWith(".tif")) {
                coverage = IOImage.loadTiff(f);
            } else {
                coverage = new RSTGridReader(f).read(null);
            }
            if(!coverage.getEnvelope2D().intersects(project.getZone())) {
                JOptionPane.showMessageDialog(this, "Raster does not intersect study area.");
                return;
            }

            extVars.put(coverage.getName().toString(), coverage);
            ((DefaultTableModel)table.getModel()).addRow(new Object [] {
                "ext-" + coverage.getName().toString(), 1.0 });

        } catch (IOException ex) {
            Logger.getLogger(ModelDialog.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "An error occured :\n" + ex.getLocalizedMessage());
        }
}//GEN-LAST:event_addExtButtonActionPerformed

    private void remVarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remVarButtonActionPerformed
        int ind = table.getSelectedRow();
        if(ind < 1) {
            return;
        }
        String name = (String) table.getValueAt(ind, 0);
        ((DefaultTableModel)table.getModel()).removeRow(ind);
        if(name.startsWith("ext-")) {
            extVars.remove(name);
        }

    }//GEN-LAST:event_remVarButtonActionPerformed

    private void addPatchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPatchButtonActionPerformed
        List<String> vars = new ArrayList<>();
        vars.addAll(project.getPatches().iterator().next().getAttributeNames());
        
        String var = (String)JOptionPane.showInputDialog(this, "Add variable : ", "Variable",
                JOptionPane.PLAIN_MESSAGE, null, vars.toArray(), vars.get(0));
        if(var == null) {
            return;
        }

        ((DefaultTableModel)table.getModel()).addRow(new Object[] {var, 1.0});
}//GEN-LAST:event_addPatchButtonActionPerformed



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addExtButton;
    private javax.swing.JButton addPatchButton;
    private javax.swing.JTextField alphaTextField;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox costComboBox;
    private javax.swing.JSpinner dMaxSpinner;
    private javax.swing.JSpinner dSpinner;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox multiAttachCheckBox;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton okButton;
    private javax.swing.JSpinner pSpinner;
    private javax.swing.JButton remVarButton;
    private javax.swing.JSpinner resolSpinner;
    private javax.swing.JTable table;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
