package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.PageKeyHandler;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;

public class BuiltInDS implements EntryPoint {
	private ListGrid boundList;
	private IButton newRowBtn;

	public void onModuleLoad() {
		KeyIdentifier debugKey = new KeyIdentifier();
		debugKey.setCtrlKey(true);
		debugKey.setKeyName("D");

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

		IButton recreateBtn = new IButton("Recreate");
		recreateBtn.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				recreate();
			}
		});
		recreate();
		recreateBtn.draw();
	}

	private void recreate() {
		Window w = new Window();
		w.setWidth("95%");
		w.setHeight("95%");
		w.setMembersMargin(0);
		w.setModalMaskOpacity(70);
		w.setTitle("Import data");
		w.setShowMinimizeButton(false);
		w.setIsModal(true);
		w.setShowModalMask(true);
		w.centerInPage();

		boundList = new ListGrid(DataSource.get("employees"));
		boundList.setHeight(600);
		boundList.setCanEdit(true);

		ListGridField name = new ListGridField("Name");
		ListGridFieldReportsTo reportsTo = new ListGridFieldReportsTo("ReportsTo");
		ListGridField job = new ListGridField("Job");
		ListGridField email = new ListGridField("Email");

		boundList.setFields(name, reportsTo, job, email);
		boundList.setSortField("Name");
		boundList.setAutoFetchData(false);
		boundList.fetchData();
		w.addItem(boundList);

		newRowBtn = new IButton("Add Row");
		newRowBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				boundList.startEditingNew();
			}
		});
		w.addItem(newRowBtn);
		w.show();
	}

	public class ListGridFieldReportsTo extends ListGridField {
		public ListGridFieldReportsTo(String name) {
			super(name);

			setEditorProperties(new SelectItemReportsTo(name));
			setFilterEditorProperties(new SelectItemReportsTo(name) {
				{
					setMultiple(true);
				}
			});

			setCanGroupBy(false);
		}
	}

	public class SelectItemReportsTo extends SelectItem {
		public SelectItemReportsTo(String name) {
			super(name);
			setOptionDataSource(DataSource.get("employees2"));
			setValueField(DataSource.get("employees2").getPrimaryKeyFieldName());
			setFetchMissingValues(true);
			setDisplayField("Name");
			setSortField("Name");
		}
	}
}