/*
	Author: Brian Alliet
	Course: 340
	Date:   April 15, 2002
	Assignment: Programming Project

	Description: A formatter class that filters input based on the
				 given criteria
 */ 

import com.brian_web.cocoalike.*;

public class FilterFormatter implements Formatter {
	private boolean insensitive;
	private boolean skipZeros;
	private String maxString;
	private int checkStart;
	private CharacterSet validChars;

	/* Sets the max string that can be entered. This isn't quite what it sounds like
		If maxString is set to "100", you can enter "2" even though "2" is greater
		that "100". The maxString only applies if the input is the same length as the
		masString. So in the "100" case you couldn't enter "101" */
	public void setMaxString(String s){
		maxString = s;
	}

	/* Sets if all the checks are case insensitive */
	public void setInsensitive(boolean b){
		insensitive = b;
	}

	/* Sets if initial '0''s are counter towards the maxString */
	public void setSkipZeros(boolean b){
		skipZeros = b;
	}

	/* Sets the character to start the checks on */
	public void setCheckStart(int n){
		checkStart = n;
	}

	/* Sets which characters are valid */
	public void setValidChars(CharacterSet set){
		validChars = set;
	}

	/* Returns the object for the input */
	public Object getObjectValueForString(String s){
		if(insensitive)
			s = s.toLowerCase();
		return s;
	}

	/* Returns a string for the given object (should usually be wharever we
		returned above */
	public String stringForObjectValue(Object o) {
		if(o instanceof String)
			return (String)o;
		else
			return null;
	}

	/* Returns true if the given string if valid. If it isn't
		return an error message in pError */
	public boolean isPartialStringValid(String partialString,Pointer pError) {
		int length;
		int start = checkStart;
		int i;
		String s;

		if(insensitive)
			s = partialString.toLowerCase();
		else
			s = partialString;

		length = s.length();

		if(length < start)
			return true;

		if(skipZeros)
			while(start < length && s.charAt(start) == '0')
				start++;

		if(validChars != null) {
			for(i=start;i<length;i++) {
				if(!validChars.characterIsMember(s.charAt(i))){
					pError.object = "" + s.charAt(i) + " is not a valid character";
					return false;
				}
			}
		}

		if(maxString != null) {
			int maxLength = maxString.length();
			if(length - start > maxLength){
				pError.object = "Input too long";
				return false;
			} else if(length - start == maxLength) {
				if(s.substring(start).compareTo(maxString)>0){
					pError.object = "Input too great";
					return false;
				}
			}
		}
		return true;
	}
}
