package com.xmltravel.fab1.wicket.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import wicket.Component;
import wicket.ajax.AjaxRequestTarget;
import wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import wicket.markup.html.form.Button;
import wicket.markup.html.form.DropDownChoice;
import wicket.markup.html.form.Form;
import wicket.model.AbstractReadOnlyModel;
import wicket.model.BoundCompoundPropertyModel;
import wicket.model.IModel;

public class ChoiceForm extends Form 
{

	private static final long serialVersionUID = 1L;
	private Map modelsMap = new HashMap(); // map:company->model

	private BoundCompoundPropertyModel inputModel;
	public ChoiceForm(String id)
	{
		super(id);
		final ChoiceModel cmodel =new ChoiceModel();
		inputModel = new BoundCompoundPropertyModel(cmodel);
		setModel(inputModel);
		renderForm(cmodel);
	}
	@SuppressWarnings("unchecked")
	private void renderForm(final ChoiceModel cmodel)
	{
		modelsMap.put("AUDI", Arrays.asList(new String[] { "A4", "A6", "TT" }));
		modelsMap.put("CADILLAC", Arrays.asList(new String[] { "CTS", "DTS", "ESCALADE", "SRX",
				"DEVILLE" }));
		modelsMap.put("FORD", Arrays.asList(new String[] { "CROWN", "ESCAPE", "EXPEDITION",
				"EXPLORER", "F-150" }));

		IModel makeChoices = new AbstractReadOnlyModel()
		{
			public Object getObject(Component component)
			{
				Set keys = modelsMap.keySet();
				List list = new ArrayList(keys);
				return list;
			}

		};

		IModel modelChoices = new AbstractReadOnlyModel()
		{
			public Object getObject(Component component)
			{
				List models = (List)modelsMap.get(cmodel.getMakes());
				if (models == null)
				{
					models = Collections.EMPTY_LIST;
				}
				return models;
			}

		};
		
		final DropDownChoice makes = new DropDownChoice("makes", makeChoices);

		final DropDownChoice models = new DropDownChoice("models", modelChoices);
		models.setOutputMarkupId(true);
	
		add(makes);
		add(models);
	
		makes.add(new AjaxFormComponentUpdatingBehavior("onchange")
		{
			protected void onUpdate(AjaxRequestTarget target)
			{
				target.addComponent(models);
			}
		});
		
		Button search = new Button("search")
		{
			
			private static final long serialVersionUID = 1L;

			protected void onSubmit() 
			{
				System.out.println(cmodel.getMakes());
				System.out.println(cmodel.getModels());
			}
			
		};
		add(search);
	}
}


