package org.greenstone.gatherer.gui;

import java.awt.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class EmailField
    extends JTextField 
    implements DocumentListener {

    static final public Pattern EMAIL_PATTERN = Pattern.compile("([^()\\-<> @,;:\"][^()<> @,;:\"]*|\"[^()<>@,;:\"]+\")@([A-Za-z](-*[A-Za-z0-9])*(\\.[A-Za-z](-*[A-Za-z0-9])*)*)");

    private boolean invalid = false;
    private Color background;
    private Color invalid_background;

    public EmailField(Color invalid_background) {
	super();
	this.invalid_background = invalid_background;
    }

    public EmailField(String email, Color invalid_background) {
	super(email);
	this.invalid_background = invalid_background;
    }

    /** Gives notification that an attribute or set of attributes changed.
     * @param e
     */
    public void changedUpdate(DocumentEvent e) {
	validateEmail();
    }
          
    /** Gives notification that there was an insert into the document.
     * @param e
     */
    public void insertUpdate(DocumentEvent e) {
	validateEmail();
    }
          
    /** Gives notification that a portion of the document has been removed. 
     * @param e
     */
    public void removeUpdate(DocumentEvent e) {
	validateEmail();
    }

    private void validateEmail() {
	Matcher m = EMAIL_PATTERN.matcher(getText());
	if(m.matches()) {
	    // It was invalid, but now its valid again
	    if(invalid) {
		setBackground(background);
		invalid = false;
	    }
	    // Otherwise nothings changed so why do anything
	}
	else {
	    background = getBackground();
	    setBackground(invalid_background);
	    invalid = true;
	}
	m = null;
    }
}
