// Copyright 2001-2005, Danger, Inc.  All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/

package com.example.GUIDemo;

import java.util.Vector;

import danger.app.Application;
import danger.text.Collator;
import danger.text.DangerCollator;
import danger.ui.ListSelectMenu;
import danger.ui.MenuItem;
import danger.util.TextFinder;

/**
 * Utility class for demonstrating TextFinder functionality. This is used for
 * the TypeAheadTextField and used to demonstrate the ListSelectMenu.
 * 
 * Even though ListSelectMenu is a subclass of Menu, it is not possible to use
 * Menu methods like addItem() to manage this menu. 
 */
public class FruitFinder implements TextFinder, Resources {

	// Read in the StringArray with all searchable fruit names. It is made
	// static final to avoid recreating these strings that do not change.
	private static final String[] kFruit = Application.getCurrentApp()
			.getStringArray(ID_FRUIT_STRINGS);

	// A Vector is used here instead of a MenuItem[] because the Vector
	// will manage memory better than recreating the array each time
	// through. The search is called for each character typed.
	private static Vector sItems = new Vector();

	public FruitFinder() {
	}

	// The search uses the key, and provides a Vector with any matching
	// results. All sItems are first removed, to ensure an accurate list.
	// Using DangerCollator is superior to other string comparisons.
	public void search(ListSelectMenu menu, String key) {
		DangerCollator collator = (DangerCollator) DangerCollator.getInstance();
	
		sItems.removeAllElements();
		for (int i = 0; i < kFruit.length; i++) {
			if (collator.startsWith(kFruit[i], key, Collator.PRIMARY)) {
				sItems.addElement(new MenuItem(kFruit[i]));
			}
		}
		// After all are found, the menu must be updated with the newly
		// created Vector.
		menu.updateMenuContents(sItems);
	}
}
