package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItemCriteriaFunction;
import com.smartgwt.client.widgets.form.fields.FormItemFunctionContext;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.layout.VStack;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class DataSourceDMI implements EntryPoint {

	private SelectItem dynamicFlag1Item;
	private SelectItem dynamicFlag2Item;
	private SelectItem dynamicFlag3Item;
    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
        VStack vStack = new VStack();
        vStack.setLeft(175);
        vStack.setTop(75);
        vStack.setWidth("70%");
        vStack.setMembersMargin(20);

        Button button = new Button("xxx");

        button.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
              int num1 = 1+event.getX()%4;
              dynamicFlag1Item.setValue(""+num1);
              int num2 = 5+event.getX()%2;
              dynamicFlag2Item.setValues(new String[]{""+num2,""+(num2+1)});
              int num4 = 8+event.getX()%2;
              dynamicFlag3Item.setValue(""+num4);
			}
		});
        vStack.addMember(button);

        DynamicForm boundForm = new DynamicForm();

        dynamicFlag1Item = createDynamicFlag(1);
        dynamicFlag2Item = createDynamicFlag(2);
        dynamicFlag3Item = createDynamicFlag(3);
        boundForm.setFields(dynamicFlag1Item, dynamicFlag2Item, dynamicFlag3Item);
        dynamicFlag2Item.setMultiple(true);
        
        vStack.addMember(boundForm);

        vStack.draw();
    }
    
    private SelectItem createDynamicFlag(final int positionIndex) {
		SelectItem dynamicFlag = new SelectItem("flag"+positionIndex);
		dynamicFlag.setWidth(300);
		dynamicFlag.setTitle("name"+positionIndex);
		dynamicFlag.setRequired(true);
		dynamicFlag.setAllowEmptyValue(false);
		dynamicFlag.setOptionDataSource(DataSource.get("brancheFlagDS"));
		dynamicFlag.setAlwaysFetchMissingValues(true);
		dynamicFlag.setValueField("id");
		dynamicFlag.setDisplayField("name");
		dynamicFlag.setPickListFilterCriteriaFunction(new FormItemCriteriaFunction() {
			@Override
			public Criteria getCriteria(FormItemFunctionContext itemContext) {
				Criteria criteria = new Criteria();
				criteria.addCriteria("flagId", positionIndex);
				return criteria;
			}
		});
		return dynamicFlag;
	}
}
