/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2011 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 2011 Sun Microsystems, Inc.
 */
package org.nbphpcouncil.modules.php.ci.ui.options;

import java.io.File;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import org.nbphpcouncil.modules.php.ci.CIVersion;
import org.nbphpcouncil.modules.php.ci.repository.CIFile;
import org.nbphpcouncil.modules.php.ci.repository.CIRepositories;
import org.nbphpcouncil.modules.php.ci.support.Utils;
import org.openide.DialogDescriptor;
import org.openide.NotificationLineSupport;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;

/**
 *
 * @author Junji Takakura
 */
public class CIEntryEditPanel extends javax.swing.JPanel {

    private static final long serialVersionUID = 1L;
    private static File lastZipFolder = null;
    private DialogDescriptor validityDescriptor;
    private NotificationLineSupport validityNotificationSupport;
    private CIVersion version;
    private Map<String, String> fileEntryMap;

    public CIEntryEditPanel() {
        initComponents();
    }

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

        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        pathLabel = new javax.swing.JLabel();
        pathTextField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();

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

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

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

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

        browseButton.setText(org.openide.util.NbBundle.getMessage(CIEntryEditPanel.class, "CIEntryEditPanel.browseButton.text")); // NOI18N
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        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(nameLabel)
                    .addComponent(pathLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                    .addComponent(pathTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(browseButton)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathLabel)
                    .addComponent(pathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setFileHidingEnabled(false);
        setHelpToChooser(chooser);
        chooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return (file.isDirectory() || file.getName().endsWith(".zip")); // NOI18N
            }

            @Override
            public String getDescription() {
                return getMessage("CTL_ZipArchivesMask"); // NOI18N
            }
        });

        if (lastZipFolder != null) {
            chooser.setCurrentDirectory(lastZipFolder);
        }

        chooser.setDialogTitle(getMessage("CTL_ZipDialogTitle"));
        chooser.setMultiSelectionEnabled(false);

        if (chooser.showDialog(this, getMessage("CTL_ApproveButtonTitle")) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();

            if (file != null && file.isFile()) {
                String path = file.getAbsolutePath();

                if (path != null) {
                    pathTextField.setText(path.trim());
                }

                detectVersion(file);
                
                String name = generateUniqueName();
                
                if (name != null) {
                    nameTextField.setText(name.trim());
                }

                lastZipFolder = chooser.getCurrentDirectory();
            }
        }
    }//GEN-LAST:event_browseButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JLabel pathLabel;
    private javax.swing.JTextField pathTextField;
    // End of variables declaration//GEN-END:variables

    void load(CIEntry entry) {
        assert entry != null;

        nameTextField.setText(entry.getName());
        pathTextField.setText(entry.getPath());

        if (entry.getVersion() != null) {
            version = new CIVersion(entry.getBranch(), entry.getVersion());
        }
    }

    void store(CIEntry entry) {
        assert entry != null;

        entry.setName(nameTextField.getText().trim());
        entry.setPath(pathTextField.getText().trim());

        if (version != null) {
            entry.setBranch(version.getBranch());
            entry.setVersion(version.getVersion());
        }
    }

    void setFileEntryMap(Map<String, String> fileEntryMap) {
        this.fileEntryMap = fileEntryMap;
    }

    void setValidityObjects(DialogDescriptor validityDescriptor, NotificationLineSupport validityNotificationSupport) {
        this.validityDescriptor = validityDescriptor;
        this.validityNotificationSupport = validityNotificationSupport;
        attachValidityChecks();
    }

    private void attachValidityChecks() {
        DocumentListener validityDocumentListener = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                checkValid();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                checkValid();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                checkValid();
            }
        };

        nameTextField.getDocument().addDocumentListener(validityDocumentListener);
        pathTextField.getDocument().addDocumentListener(validityDocumentListener);
        checkValid();
    }

    private boolean checkValidName() {
        boolean isValid = false;

        String name = nameTextField.getText().trim();

        // TODO add characters length check(80).

        if (name == null || name.trim().length() == 0) {
            validityDescriptor.setValid(false);
            validityNotificationSupport.setErrorMessage(getMessage("MSG_EmptyName"));
        } else if (fileEntryMap.containsKey(name)) {
            validityDescriptor.setValid(false);
            validityNotificationSupport.setErrorMessage(getMessage("MSG_ExistingName"));
        } else {
            isValid = true;
        }

        return isValid;
    }

    private boolean checkValidPath() {
        boolean isValid = false;

        String path = pathTextField.getText().trim();

        // TODO add characters length check(8192 - MAX_VALUE_LENGTH).

        if (path == null || path.trim().length() == 0) {
            validityDescriptor.setValid(false);
            validityNotificationSupport.setErrorMessage(getMessage("MSG_EmptyPath"));
        } else if (fileEntryMap.containsValue(path)) {
            validityDescriptor.setValid(false);
            validityNotificationSupport.setErrorMessage(getMessage("MSG_ExistingPath"));
        } else if (!new File(path).isFile()) {
            validityDescriptor.setValid(false);
            validityNotificationSupport.setErrorMessage(getMessage("MSG_InvalidPath"));
        } else {
            isValid = true;
        }

        return isValid;
    }

    private void checkValid() {
        if (validityNotificationSupport == null) {
            return;
        }

        if (checkValidName() && checkValidPath()) {
            validityDescriptor.setValid(true);
            validityNotificationSupport.clearMessages();
        }
    }

    private void detectVersion(File file) {
        if (file != null && file.isFile()) {
            Set<CIFile> files = CIRepositories.getInstance().getAllFiles();
            String md5sum = Utils.getMD5Sum(file);
            String sha1sum = Utils.getSHA1Sum(file);

            version = null;

            if (md5sum != null && sha1sum != null) {
                for (CIFile f : files) {
                    if (!md5sum.equals(f.getMd5Sum())) {
                        // TODO implements to add logger??
                    } else if (!sha1sum.equals(f.getSha1Sum())) {
                        // TODO implements to add logger??
                    } else {
                        version = new CIVersion(f.getBranch(), f.getVersion());
                        break;
                    }
                }
            }
        }
    }

    private String generateUniqueName() {
        String name = null;

        if (version != null) {
            name = version.toString();
        }

        if (name == null) {
            name = getMessage("LBL_CIUnsupportedVersion");
        }

        if (fileEntryMap.containsKey(name)) {
            int index = 1;
            StringBuilder sb = new StringBuilder();

            do {
                sb.delete(0, sb.length());
                sb.append(name).append("_(").append(index).append(")");
                index++;
            } while (fileEntryMap.containsKey(sb.toString()));

            name = sb.toString();
        }

        return name;
    }

    private String getMessage(String resourceName, Object... parameters) {
        return NbBundle.getMessage(CategoryArchiveFiles.class, resourceName, parameters);
    }

    private void setHelpToChooser(JFileChooser chooser) {
        HelpCtx help = HelpCtx.findHelp(this);

        if (help != null) {
            HelpCtx.setHelpIDString(chooser, help.getHelpID());
        }
    }
}