/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
 *
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
 * Other names may be trademarks of their respective owners.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 *
 * Contributor(s):
 *
 * Portions Copyrighted 2010 Sun Microsystems, Inc.
 */

package org.netbeans.modules.apisupport.crudsample;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.netbeans.api.project.libraries.Library;
import org.netbeans.api.project.libraries.LibraryManager;
import org.netbeans.modules.derby.spi.support.DerbySupport;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileUtil;

/**
 *
 * @author jirka
 */
public class SampleAppWizardExtraVisual extends JPanel implements DocumentListener {
    public static final String[] SUPPORTED_PU_LIBRARIES = new String[] {"eclipselink"};
    public static final String JAVADB_HOME = "javadb.home";

    private final SampleAppWizardExtraPanel panel;
    private Map<String, Library> dn2lib = new HashMap<String, Library>();

    /** Creates new form SampleAppWizardExtraPanelVisual */
    @SuppressWarnings("LeakingThisInConstructor")
    public SampleAppWizardExtraVisual(SampleAppWizardExtraPanel panel) {
        initComponents();
        this.panel = panel;
        this.cbLibrary.setModel(new DefaultComboBoxModel(getLibrariesDN()));
        this.tfDerby.setText(getDerbyInstallation());
        this.tfDerby.getDocument().addDocumentListener(this);
    }

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

        lDerby = new javax.swing.JLabel();
        tfDerby = new javax.swing.JTextField();
        bDerby = new javax.swing.JButton();
        lDerbyHint = new javax.swing.JLabel();
        lLibarary = new javax.swing.JLabel();
        cbLibrary = new javax.swing.JComboBox();

        lDerby.setLabelFor(tfDerby);
        org.openide.awt.Mnemonics.setLocalizedText(lDerby, org.openide.util.NbBundle.getMessage(SampleAppWizardExtraVisual.class, "SampleAppWizardExtraVisual.lDerby.text")); // NOI18N

        tfDerby.setColumns(280);
        tfDerby.setText(org.openide.util.NbBundle.getMessage(SampleAppWizardExtraVisual.class, "SampleAppWizardExtraVisual.tfDerby.text")); // NOI18N

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

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

        lLibarary.setLabelFor(cbLibrary);
        org.openide.awt.Mnemonics.setLocalizedText(lLibarary, org.openide.util.NbBundle.getMessage(SampleAppWizardExtraVisual.class, "SampleAppWizardExtraVisual.lLibarary.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)
                    .addComponent(lDerby)
                    .addComponent(lLibarary))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lDerbyHint)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfDerby, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                        .addGap(9, 9, 9)
                        .addComponent(bDerby))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cbLibrary, 0, 202, Short.MAX_VALUE)
                        .addGap(79, 79, 79)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lDerby)
                    .addComponent(tfDerby, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bDerby))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lDerbyHint)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lLibarary)
                    .addComponent(cbLibrary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bDerbyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDerbyActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(null);
        chooser.setDialogTitle(org.openide.util.NbBundle.getMessage(SampleAppPanelVisual.class, "SampleAppPanelVisual.select_derby_location"));
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        String path = this.tfDerby.getText();
        if (path.length() > 0) {
            File f = new File(path);
            if (f.exists()) {
                chooser.setSelectedFile(f);
            }
        }
        if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
            File projectDir = chooser.getSelectedFile();
            tfDerby.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
        }
        panel.fireChangeEvent();
    }//GEN-LAST:event_bDerbyActionPerformed

    @Override
    public void insertUpdate(DocumentEvent e) {
        panel.fireChangeEvent();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        panel.fireChangeEvent();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        panel.fireChangeEvent();
    }

    boolean valid(WizardDescriptor wizardDescriptor) {
        if (! validateDerby(tfDerby.getText())) {
            if (wizardDescriptor != null) {
                wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE,
                    org.openide.util.NbBundle.getMessage(SampleAppWizardExtraVisual.class, "SampleAppWizardExtraVisual.invalid_derby_location"));
            }
            return false;
        } else if (! validatePersistenceLibrary()) {
            if (wizardDescriptor != null) {
                wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE,
                    org.openide.util.NbBundle.getMessage(SampleAppWizardExtraVisual.class, "SampleAppWizardExtraVisual.invalid_persistence_libraries"));
            }
            return false;
        } else {
            if (wizardDescriptor != null) {
                wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null);
            }
            return true;
        }
    }

    void validate(WizardDescriptor wizardDescriptor) {}

    private String[] getLibrariesDN() {
        List<String> res = new ArrayList<String>();
        for (String name : SUPPORTED_PU_LIBRARIES) {
            Library l = LibraryManager.getDefault().getLibrary(name);
            Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).log(Level.FINE, "Name {0} has library {1}", new Object[]{name, l});
            if (l != null) {
                res.add(l.getDisplayName());
                dn2lib.put(l.getDisplayName(), l);
            }
        }
        return res.toArray(new String[0]);
    }

    private Library getLibrary(String dn) {
        assert dn2lib.get(dn) != null : "Library " + dn + " found in " + dn2lib;
        return dn2lib.get(dn);
    }

    private static String getDerbyInstallation() {
        File f = null;
        String javaDBHome = System.getProperty(JAVADB_HOME);
        Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).finest("System.getProperty(\"javadb.home\") returns " + javaDBHome);
        if (javaDBHome == null) {
            String javaDBLoc = DerbySupport.getLocation();
            Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).finer("DerbySupport.getLocation() returns " + javaDBLoc);
            if (javaDBLoc != null && javaDBLoc.length() > 0) {
                f = new File(javaDBLoc);
            }
            if (f == null || ! f.exists()) {
                // fallback to JDK6
                String javaHome = System.getProperty("java.home");
                // path to JavaDB in JDK6
                f = new File(javaHome + File.separator + ".." + File.separator + "db" + File.separator);
                Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).finer("JavaDB in JDK6 is " + f);
            }
        } else {
            f = new File(javaDBHome);
        }
        String path;
        try {
            path = f != null && f.exists() ? f.getCanonicalPath() : null;
        } catch (IOException ex) {
            path = f != null && f.exists() ? f.getAbsolutePath() : null;
        }
        Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).fine("Java DB installation is " + path);
        return path;
    }

    private static boolean validateDerby(String path) {
        boolean res = path != null;
        if (res) {
            File dir = new File(path);
            res = dir.exists() && dir.isDirectory();
            if (res) {
                // finding derbyclient
                File f = new File(dir, "lib" + File.separator + "derbyclient.jar");
                res = f.exists() && f.isFile();
            }
        }
        return res;
    }

    private boolean validatePersistenceLibrary() {
        return getLibrariesDN().length > 0;
        // XXX: maybe also check if drivers really exist
    }

    String getDerbyLocation() {
        assert validateDerby(tfDerby.getText()) : "DB Location " + tfDerby.getText() + " must contain lib/derbyclient.jar";
        return tfDerby.getText();
    }

    Library getSelectedLibrary() {
        assert getLibrary((String) cbLibrary.getSelectedItem()) != null : "Some Persistence Library must found.";
        Logger.getLogger(SampleAppWizardExtraVisual.class.getName()).log(Level.FINE,
                "Selected library in {0} is {1}", new Object[]{cbLibrary.getSelectedItem(), getLibrary((String) cbLibrary.getSelectedItem())});
        return getLibrary((String) cbLibrary.getSelectedItem());
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    javax.swing.JButton bDerby;
    javax.swing.JComboBox cbLibrary;
    javax.swing.JLabel lDerby;
    javax.swing.JLabel lDerbyHint;
    javax.swing.JLabel lLibarary;
    javax.swing.JTextField tfDerby;
    // End of variables declaration//GEN-END:variables

}
