/* Copyright 2000 by Basil Vandegriend.  All rights reserved. */

package com.basilv.core.richui;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import com.basilv.core.Assert;

/**
 * Document permitting only whole numbers.
 */
public class WholeNumberDocument extends PlainDocument
{
	private static final long serialVersionUID = 1L;

	private int maxDigits = 0;

	/**
	 * Create an instance that limits the document to the specified number of
	 * digits.
	 * 
	 * @param newMaxDigits  Must be > 0.
	 */
	public WholeNumberDocument(int newMaxDigits) {
		Assert.greaterThanZero("newMaxDigits", newMaxDigits);
		maxDigits = newMaxDigits;
	}

	/**
	 * Set the maximum number of digits of the document. The current text is not
	 * modified if it exceeds this new maximum.
	 * 
	 * @param newMaxDigits  Must be > 0.
	 */
	public void setMaxDigits(int newMaxDigits) {
		Assert.greaterThanZero("newMaxDigits", newMaxDigits);
		maxDigits = newMaxDigits;
	}

	/**
	 * Only allow the insertion if the result is a valid number.
	 */
	@Override
	public void insertString(int insertOffset, String insertStr, 
		AttributeSet attributeSet) throws BadLocationException {

		if (insertStr == null) {
			return;
		}

		// Validate that the insertion string only contains digits
		for (int charIndex = 0; charIndex < insertStr.length(); charIndex++) {
			if (!Character.isDigit(insertStr.charAt(charIndex))) {
				return;
			}
		}

		// Now check that the max digits will not be exceeded.
		int newLength = getLength() + insertStr.length();
		if (newLength <= maxDigits) {
			// Contents are a valid string that does not exceed the
			// maximum number of digits, so accept the string.
			super.insertString(insertOffset, insertStr, attributeSet);
		}
	}

} // class WholeNumberDocument
