package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.util.EventHandler;
import com.smartgwt.client.util.KeyCallback;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FloatItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
import com.smartgwt.client.widgets.layout.VLayout;

public class TabbingIssue implements EntryPoint {

	private DynamicForm form;

    public void onModuleLoad() {

        
		KeyIdentifier debugKey = new KeyIdentifier();
		debugKey.setCtrlKey(true);
		debugKey.setKeyName("D");

		Page.registerKey(debugKey, new KeyCallback() {
			public void execute(String keyName) {
				SC.showConsole();
			}
		});

        VLayout example = new VLayout();
        
        form = new DynamicForm();
        form.setNumCols(4);
        TextItem text1 = new TextItem();
        FloatItem float1 = makeFloatItem();
        TextItem text2 = new TextItem();
        FloatItem float2 = makeFloatItem();
        
        form.setItems(text1, float1, text2, float2);
        example.addMember(form);
        
        
        example.draw();
    }
    
    private FloatItem makeFloatItem() {
    	FloatItem floatItem = new FloatItem();
        floatItem.addKeyPressHandler(new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				System.out.println("User hit key: " + event.getKeyName());
				if (("Tab".equals(event.getKeyName()) == true)
						&& (EventHandler.shiftKeyDown() == false)) {
					FormItem fields[] = form.getFields();
					FormItem currentItem = event.getItem();
					FormItem lastItem = fields[fields.length - 1];
					if (currentItem.equals(lastItem)) {						
						event.cancel();					
						addNewRow();
					}
				}
			}
		});
        
        return floatItem;
    }
    
	protected void addNewRow() {
		FormItem fields[] = form.getFields();
		FormItem moreFields[] = new FormItem[fields.length + 2];
		System.arraycopy(fields, 0, moreFields, 0, fields.length);
		moreFields[fields.length] = new TextItem();
		moreFields[fields.length + 1] = makeFloatItem();

		form.setFields(moreFields);
		form.redraw();
		moreFields[fields.length].focusInItem();

		
	}

}
