package com.testApp.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.KeyPressEvent;
import com.smartgwt.client.widgets.events.KeyPressHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyUpEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyUpHandler;
import com.smartgwt.client.widgets.layout.VLayout;

public class TestApp implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		VLayout mainLayout = createMainLayout();

		Label welcomeLabel = new Label("Press [SPACE] to display the focused item.");
		welcomeLabel.setWidth(100);

		final Label messageLabel = new Label();
		messageLabel.setWidth(100);

		final DynamicForm dynamicForm = createDynamicForm();
		dynamicForm.setFields(createTextItem("One"), createTextItem("Two"), createTextItem("Three"));
		dynamicForm.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent keyPressEvent) {
				if (keyPressEvent.getKeyName().equalsIgnoreCase("space")) {
					FormItem itemInFocus = dynamicForm.getFocusItem();
					String message = "DynamicForm.getFocusItem() returned ";
					if (itemInFocus != null) {
						if(itemInFocus.isFocused()){
							messageLabel.setContents(message + itemInFocus.getName());
						}
						else {
							messageLabel.setContents(message + itemInFocus.getName() + " but it is not in focus.");
						}
					}
					else {
						messageLabel.setContents(message + "null");
					}
				}
			}
		});

		mainLayout.addMembers(welcomeLabel, dynamicForm, messageLabel);
		dynamicForm.focus();

		mainLayout.show();
	}

	public static VLayout createMainLayout(){
		VLayout vlayout = new VLayout();
		vlayout.setWidth100();
		vlayout.setPadding(20);
		vlayout.setMembersMargin(20);
		vlayout.setAlign(Alignment.CENTER);
		return vlayout;
	}

	public static DynamicForm createDynamicForm(){
		DynamicForm dynamicForm = new DynamicForm();
		dynamicForm.setWidth(100);
		dynamicForm.setHeight(100);
		return dynamicForm;
	}

	public static TextItem createTextItem(final String title){
		final TextItem textItem = new TextItem(title);
		textItem.setTitle(title);
		textItem.addKeyUpHandler(new KeyUpHandler() {
			public void onKeyUp(KeyUpEvent keyUpEvent) {
				if (keyUpEvent.getKeyName().equalsIgnoreCase("escape")) {
					if (textItem.isFocused()) {
						textItem.blurItem();
					}
				}
			}
		});
		return textItem;
	}
}
