/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * NBLoginPanel.java
 *
 * Created on Jan 22, 2010, 11:02:27 AM
 */

package org.netbeans.modules.bugzilla.repository;

import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.netbeans.modules.bugtracking.commons.LinkButton;
import org.netbeans.modules.bugzilla.Bugzilla;
import org.netbeans.modules.bugzilla.util.BugzillaUtil;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.awt.HtmlBrowser.URLDisplayer;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;

/**
 *
 * @author Tomas Stupka
 */
class NBLoginPanel extends javax.swing.JPanel {

    private final JButton login = new JButton(NbBundle.getMessage(NBLoginPanel.class, "LBL_Login"));      // NOI18N
    private final JButton cancel = new JButton(NbBundle.getMessage(NBLoginPanel.class, "LBL_Cancel"));    // NOI18N

    /** Creates new form NBLoginPanel */
    NBLoginPanel() {
        initComponents();
        errorLabel.setVisible(false);

        login.getAccessibleContext().setAccessibleDescription(login.getText());
        cancel.getAccessibleContext().setAccessibleDescription(cancel.getText());
        usernameTextField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                validateFields();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                validateFields();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
                validateFields();
            }
        });
    }

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

        jLabel1 = new javax.swing.JLabel();
        usernameTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new LinkButton(new NBRegisterAction());
        passwordField = new javax.swing.JPasswordField();
        errorLabel = new javax.swing.JLabel();

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

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

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

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

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

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

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

        errorLabel.setForeground(BugzillaUtil.getErrorForegroundColor());
        errorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/netbeans/modules/bugzilla/resources/error.gif"))); // NOI18N
        errorLabel.setText(org.openide.util.NbBundle.getMessage(NBLoginPanel.class, "NBLoginPanel.errorLabel.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)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(passwordField)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(errorLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(usernameTextField, 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(jLabel3)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(errorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel errorLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables

    private class NBRegisterAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                URLDisplayer.getDefault().showURL(new URL(NBRepositorySupport.URL_NB_ORG_SIGNUP)); 
            } catch (MalformedURLException ex) {
                Bugzilla.LOG.log(Level.SEVERE, NAME, ex);
            }
        }
    }

    static boolean show(final BugzillaRepository repo, String errorMsg) {
        final NBLoginPanel panel = new NBLoginPanel();
        panel.usernameTextField.setText(repo.getUsername());
        panel.passwordField.setText(new String(repo.getPassword()));
        panel.validateFields();
        panel.updateErrorMessage(errorMsg);
        if(panel.showLogin()) {   // NOI18N
            repo.setInfoValues(panel.usernameTextField.getText(), panel.passwordField.getPassword());
            return true;
        }
        return false;
    }

    private boolean showLogin() {
        DialogDescriptor descriptor = new DialogDescriptor (
                this,
                NbBundle.getMessage(NBLoginPanel.class, "LBL_LOGIN_2_NBORG"),   // NOI18N
                true,
                new Object[] {login, cancel},
                login,
                DialogDescriptor.DEFAULT_ALIGN,
                new HelpCtx("org.netbeans.modules.bugzilla.api.NBLoginPanel"),  // NOI18N
                null);
        return DialogDisplayer.getDefault().notify(descriptor) == login;
    }

    private void validateFields() {
        if(usernameTextField.getText().trim().equals("")) {                     // NOI18N
            login.setEnabled(false);
            updateErrorMessage(NbBundle.getMessage(NBLoginPanel.class, "MSG_MISSING_USERNAME_PASSWORD"));    // NOI18N
        } else {
            login.setEnabled(true);
            updateErrorMessage(null);
        }
    }

    private void updateErrorMessage(String errorMsg) {
        if (errorMsg != null) {
            errorLabel.setVisible(true);
            errorLabel.setText(errorMsg);
        } else {
            errorLabel.setVisible(false);
            errorLabel.setText("");                                             // NOI18N
        }
    }
}
