/*
 * PasswordEntryForm.java
 *
 * Copyright 2011 John W Dawson
 *
 * This code is distributed under the terms of the GNU General Public License, version 3
 *
 * This class implements the form used to enter the password at start up
 */
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.security.*;
import java.util.*;
public class PasswordEntryForm extends AddressBookConfigurationForm
{
  
  private JPasswordField password;
  private String passwordHash;
  private AddressBookConfiguration configuration;
   
  public PasswordEntryForm (AddressBookConfiguration configuration, JFrame mainWindow, String passwordHash) 
  {
    super ("Enter Password", null, configuration, mainWindow, 16);  
    this.passwordHash = passwordHash;
    this.configuration = configuration;
  }
  
  protected void defineFields ()
  {    
 
    // Add fields for entering password 
    password = addPasswordField ("Password:", "");
       
  }
  
 
  protected void otherAction (AbstractButton source)
  {
  }
  
  protected boolean validateAndSave ()   
  {
    // Check if user has entered a password
    if (password.getPassword().length == 0)
    {
      JOptionPane.showMessageDialog (this, "Please enter the password");
      password.requestFocus ();
      return false;
    }
    
    
    // Get MD5 hash of password and compare with value in configuration
    try
    {
      MessageDigest algorithm = MessageDigest.getInstance("MD5");
      algorithm.reset ();
      algorithm.update ((new String (password.getPassword ())).getBytes());
      if (!passwordHash.equals ((new BytesToHexBuffer (algorithm.digest())).toString()))
      {
        JOptionPane.showMessageDialog (this, "The password you entered is incorrect");
        password.setText ("");
        password.requestFocus ();
        return false;
      }
    }
    catch (NoSuchAlgorithmException e)
    {}
                                       
    // Set up encryption key in configuration
    configuration.passwordSet (new String (password.getPassword ()));

    return true;        
  }
  
  protected Boolean cancel ()
  {
    // Exit the program
    System.exit (0);
    return true;
  }
        
}    