// DoubleField.java
// $Id: DoubleField.java,v 1.1 1996/04/10 13:41:35 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.forms;

import java.util.*;

import w3c.jigsaw.html.*;

public class DoubleField extends FormField {
    Double value = null ;

    /*
     * Get this field value.
     */

    public Object getValue() {
	return value ;
    }

    /**
     * Set this field's value, by parsing the provided String.
     * @param nval The new field value.
     * @return A boolean <strong>true</strong> if the value is valid.
     */

    public boolean setValue(String nval) 
	throws FormFieldException
    {
	// Unset the field' value ?
	if ((nval == null) || nval.equals("")) {
	    boolean result = (value != null) ;
	    value = null ;
	    return result ;
	}
	// Parse the value as a double ?
	Double dval = null ;
	try {
	    dval = new Double(nval) ;
	} catch (NumberFormatException ex) {
	    String msg = "Invalid double value: " + nval ;
	    throw new FormFieldException(msg) ;
	}
	// Is this different from what we have ?
	if ( dval.equals(value) )
	    return false ;
	value = dval ;
	return true ;
    }

    /**
     * Dump this field as a form element.
     * @param into The HtmlGenerator to dump the field to.
     */

    public void dump(HtmlGenerator into) {
	dumpTitle(into) ;
	into.append ("<th align=left><input type=\"text\""
		     + " name=\""+name+"\""
		     + " size=\"32\""
		     + " value=\"" 
		     + ((value == null) ? "" : value.toString())
		     + "\"></th>");
    }

    /*
     * Initialize a DoubleField.
     * @param name The name of the field.
     * @param title Its title.
     * @param url Its url (or <strong>null</strong>).
     * @param value Its default value.
     * @exception FormFieldException If the provided value doesn't match 
     *    the expected type.
     */
    
    public void initialize(String name, String title, String url, Object val) 
	throws FormFieldException
    {
	super.initialize(name, title, url, null) ;
	try {
	    this.value = (Double) val ;
	} catch (ClassCastException ex) {
	    String msg = "Invalid type: "+val.getClass().getName() ;
	    throw new FormFieldException (msg) ;
	}
    }

    /**
     * Create a new double field.
     * @param name The name of the field.
     * @param title The title of the field.
     * @param url The URL of the field.
     * @param value Its initial value.
     */

    public DoubleField(String name, String title, String url, Double value) 
	throws FormFieldException
    {
	super(name, title, url) ;
	this.value = value ;
    }

    public DoubleField() {
    }

}
