/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (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.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.ui.dlg;

import java.io.IOException;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.ui.*;
import com.silverwrist.venice.util.XMLLoader;

public class IntegerField extends TextField
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static final double LN10 = Math.log(10.0);

  public static final String TAGNAME = "int";

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private int min_value;     // minimum value for this field
  private int max_value;     // maximum value for this field

  /*--------------------------------------------------------------------------------
   * Constructors
   *--------------------------------------------------------------------------------
   */

  public IntegerField(String name, String caption, String caption2, int min, int max)
  {
    super(name,caption,caption2,true,numDigits(min,max));
    if (min<max)
    { // assign the min and max values normally
      this.min_value = min;
      this.max_value = max;

    } // end if
    else
    { // swap the values round so they're ordered right
      this.min_value = max;
      this.max_value = min;

    } // end else

  } // end constructor

  public IntegerField(Element elt) throws ConfigException
  {
    super(elt,numDigits(elt));
    XMLLoader loader = XMLLoader.get();
    DOMElementHelper h = new DOMElementHelper(elt);
    if (h.hasAttribute("min"))
      min_value = loader.configGetAttributeInt(elt,"min");
    else
      min_value = Integer.MIN_VALUE;
    if (h.hasAttribute("max"))
      max_value = loader.configGetAttributeInt(elt,"max");
    else
      max_value = Integer.MAX_VALUE;
    if (max_value<min_value)
    { // swap round the two values to put them in the right order
      int t = min_value;
      min_value = max_value;
      max_value = t;

    } // end if

  } // end constructor

  protected IntegerField(IntegerField other)
  {
    super(other);
    this.min_value = other.min_value;
    this.max_value = other.max_value;

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Internal operations
   *--------------------------------------------------------------------------------
   */

  private static final int numDigits(int v)
  {
    if (v==0)
      return 1;
    else if (v>0)
      return 1 + (int)(Math.floor(Math.log((double)v) / LN10));
    else
      return 2 + (int)(Math.floor(Math.log((double)(-v)) / LN10));

  } // end numDigits

  private static final int numDigits(int min, int max)
  {
    return Math.max(numDigits(min),numDigits(max));

  } // end numDigits

  private static final int numDigits(Element elt) throws ConfigException
  {
    XMLLoader loader = XMLLoader.get();
    DOMElementHelper h = new DOMElementHelper(elt);
    int min, max;
    if (h.hasAttribute("min"))
      min = loader.configGetAttributeInt(elt,"min");
    else
      min = Integer.MIN_VALUE;
    if (h.hasAttribute("max"))
      max = loader.configGetAttributeInt(elt,"max");
    else
      max = Integer.MAX_VALUE;
    return numDigits(min,max);

  } // end numDigits

  /*--------------------------------------------------------------------------------
   * Overrides from class TextField
   *--------------------------------------------------------------------------------
   */

  protected void renderField(RequestOutput out) throws IOException
  {
    super.renderField(out);
    out.write("&nbsp;(" + min_value + " - " + max_value + ")");

  } // end renderField

  protected void validateContents(String value) throws ValidationException
  {
    super.validateContents(value);
    try
    { // convert to an integer and check against range
      int x = Integer.parseInt(value);
      if ((min_value>Integer.MIN_VALUE) && (x<min_value))
	throw new ValidationException("The value of the '" + getCaption()
				      + "' field must be greater than or equal to " + min_value + ".");
      if ((max_value<Integer.MAX_VALUE) && (x>max_value))
	throw new ValidationException("The value of the '" + getCaption()
				      + "' field must be less than or equal to " + max_value + ".");

    } // end try
    catch (NumberFormatException nfe)
    { // integer conversion failed
      throw new ValidationException("Invalid non-numeric character in the '" + getCaption() + "' field.");

    } // end catch

  } // end validateContents

  /*--------------------------------------------------------------------------------
   * Implementations from interface DialogField
   *--------------------------------------------------------------------------------
   */

  public Object getValue()
  {
    try
    { // map the return value into an Integer
      return new Integer(super.getValue().toString());

    } // end try
    catch (NumberFormatException nfe)
    { // we should have validated the input already...
      throw new InternalStateError("IntegerField.getValue(): this was not supposed to happen!");

    } // end catch

  } // end getValue

  public void setValue(Object o)
  {
    if (o==null)
    { // blank out the field
      super.setValue(null);
      return;

    } // end if

    int real_val;
    if (o instanceof Number)
    { // we have a number!
      Number n = (Number)o;
      real_val = n.intValue();

    } // end if
    else
    { // parse the string equivalent
      try
      { // get the integer equivalent
	real_val = Integer.parseInt(o.toString());

      } // end try
      catch (NumberFormatException nfe)
      { // just use a sensible default
	real_val = min_value;

      } // end catch

    } // end else

    // Constrain the input value and set it.
    if (real_val<min_value)
      real_val = min_value;
    else if (real_val>max_value)
      real_val = max_value;
    super.setValue(String.valueOf(real_val));

  } // end setValue

  public DialogField duplicate()
  {
    return new IntegerField(this);

  } // end duplicate

} // end class IntegerField
