package test.wicket.autocomplete.pages;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.Strings;

public class Home extends BasePage {
   public Home() {
              Form form = new Form("autocompleteForm");
        add(form);

        final AutoCompleteTextField field = new AutoCompleteTextField("autocomplete", new Model(""), CustomRenderer.INSTANCE)
        {
            protected Iterator getChoices(String input)
            {
                if (Strings.isEmpty(input))
                {
                    return Collections.EMPTY_LIST.iterator();
                }

                List choices = new ArrayList(10);

                Locale[] locales = Locale.getAvailableLocales();

                for (int i = 0; i < locales.length; i++)
                {
                    final Locale locale = locales[i];
                    final String country = locale.getDisplayCountry();
                    final String language = locale.getDisplayLanguage();
                    if (country.toUpperCase().startsWith(input.toUpperCase()))
                    {
                        choices.add(new String[]{country, language});
                        if (choices.size() == 10)
                        {
                            break;
                        }
                    }
                }

                return choices.iterator();
            }
        };
        form.add(field);

        final Label label = new Label("autocompleteLegend",field.getModel());
        label.setOutputMarkupId(true);
        form.add(label);

        field.add(new AjaxFormSubmitBehavior(form, "onchange"){
            protected void onSubmit(AjaxRequestTarget target)
            {
                target.addComponent(label);
            }
        });
   }
}
