package be.repro.client;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.TitleOrientation;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.VLayout;

public class Reprocase implements EntryPoint {
	DynamicForm configurationForm = null;

	public void onModuleLoad() {
		final VLayout layout = new VLayout(10);
		layout.addMember(getConfigurationForm());
		layout.draw();
	}
	
	private DynamicForm getConfigurationForm() {
		if (configurationForm == null) {
			configurationForm = new DynamicForm();
			configurationForm.setNumCols(3);

			StatefulButtonGroupItem changeVehicle = new StatefulButtonGroupItem();
			changeVehicle.setStartRow(true);
			changeVehicle.setColSpan(3);
			LinkedHashMap<String, String> addedOptions = new LinkedHashMap<String, String>();
			addedOptions.put("1", "keep");
			addedOptions.put("2", "new");
			changeVehicle.setValueMap(addedOptions);

			final StatefulButtonGroupItem changeConfigOptions = new StatefulButtonGroupItem();
			changeConfigOptions.setStartRow(true);
			changeConfigOptions.setColSpan(3);
			addedOptions = new LinkedHashMap<String, String>();
			addedOptions.put("3", "keep");
			addedOptions.put("4", "change");
			changeConfigOptions.setValueMap(addedOptions);

			TextItem item = new TextItem();
			item.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {
				
				public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {
					
					LinkedHashMap<String, String> addedOptions = new LinkedHashMap<String, String>();
					addedOptions.put("1", "match");
					addedOptions.put("2", "clear");
					changeConfigOptions.setValueMap(addedOptions);
					configurationForm.markForRedraw();
				}
			});

			configurationForm.setFields(
					changeVehicle,
					changeConfigOptions,
					item);
		}

		return configurationForm;
	}
	
	public class StatefulButtonGroupItem extends CanvasItem {

		private final StatefulButtonGroup group;

		public StatefulButtonGroupItem(){
			group = new StatefulButtonGroup();
			setCanvas(group);
		}

		@Override
		@SuppressWarnings("unchecked")
		public void setValueMap(LinkedHashMap values) {

			super.setValueMap(values);
			group.clearContent();

			Set<Map.Entry<String, String>> entries = values.entrySet();
			for (Entry<String, String> entry : entries) {
				group.addButton(Integer.parseInt(entry.getKey()), entry.getValue());
			}
			
			// Style buttons
			group.styleButtons();
	    }
	}

	public static native void log(String msg) /*-{
		console.log(msg);
	}-*/;
}