package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.util.PageKeyHandler;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;  
import com.smartgwt.client.widgets.IButton;
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.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;


public class BuiltInDS implements EntryPoint {
	private TreeGrid treeGrid;
	private IButton fetchBtn;
	private IButton insertBtn;
	private IButton insertChildBtn;
	private IButton saveBtn;
	private IButton discardBtn;
	private CheckboxItem autoSaveCheck;
	private DataSource treeDs;
	private String dsName;
	private Canvas htmlCanvas;  

	@Override
	public void onModuleLoad() {
		initInfo();
		initDebugKey();
		initDS();
		initTreeGrid();
		initButtons();
		initLayout();
	}

	private int insertNode(int insertChild) {
		DataSource seqDs = DataSource.get("employees_seq");
		DSRequest request = new DSRequest();
		request.setAttribute("insertChild", insertChild);
		seqDs.fetchData(null, new DSCallback() {
			public void execute(DSResponse response, Object rawData,
					DSRequest request) {
				Record r[] = response.getData();
				String newId = r[0].getAttributeAsString("nextval");
				int insertChild = request.getAttributeAsInt("insertChild");
				Tree tree = treeGrid.getTree();
				
				String parentName = tree.getParentIdField();
				String idName = tree.getIdField();

				TreeNode selNode = treeGrid.getSelectedRecord();
				treeGrid.deselectAllRecords();
				
				String parentId = null;
				if (selNode != null) {
					if (insertChild == 1) parentId = selNode.getAttribute(idName);
					else parentId = selNode.getAttribute(parentName);
				} else {
					parentId = tree.getRootValue();
				}

				TreeNode newNode = new TreeNode();
				newNode.setAttribute(parentName, parentId);
				newNode.setAttribute(idName, newId);
				tree.add(newNode);
				if (insertChild == 1) treeGrid.openFolder(selNode);
				int recordIndex = treeGrid.getRecordIndex(newNode);
				treeGrid.scrollToRow(recordIndex);
				treeGrid.startEditing(recordIndex);
			}
		}, request);
		return 0;
	}

	public void initDS() {
		dsName = "employees";
		treeDs = DataSource.get(dsName);
	}

	public void initLayout() {
		VStack vStack = new VStack();
		vStack.setLeft(0);
		vStack.setTop(0);
		vStack.setWidth100();
		vStack.setMembersMargin(10);

		vStack.addMember(htmlCanvas);
		vStack.addMember(treeGrid);

		HLayout hLayout = new HLayout(10);
		hLayout.setMembersMargin(10);
		hLayout.setHeight(22);

		hLayout.addMember(fetchBtn);
		hLayout.addMember(insertBtn);
		hLayout.addMember(insertChildBtn);
		hLayout.addMember(saveBtn);
		hLayout.addMember(discardBtn);

		vStack.addMember(hLayout);

		DynamicForm optForm = new DynamicForm();
		optForm.setWidth(300);
		optForm.setFields(autoSaveCheck);
		vStack.addMember(optForm);

		vStack.draw();

	}

	public void initButtons() {
		fetchBtn = new IButton("Fetch");
		fetchBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				treeGrid.invalidateCache();
			}
		});

		insertBtn = new IButton("Insert");
		insertBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				insertNode(0);
			}
		});
/*... */
		
		insertChildBtn = new IButton("Insert Child");
		insertChildBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				insertNode(1);
			}
		});
		
		saveBtn = new IButton("Save");
		saveBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				treeGrid.saveAllEdits();
			}
		});

		discardBtn = new IButton("Discard");
		discardBtn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				treeGrid.discardAllEdits();
			}
		});
		
		autoSaveCheck = new CheckboxItem();
		autoSaveCheck.setName("autoSave");
		autoSaveCheck.setTitle("Auto Save");
		autoSaveCheck.setValue(false);
		autoSaveCheck.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				if (autoSaveCheck.getValue().equals(true)) {
					saveBtn.disable();
					discardBtn.disable();
					treeGrid.setAutoSaveEdits(true);  
				}
				else {
					saveBtn.enable();
					discardBtn.enable();	
					treeGrid.setAutoSaveEdits(false);  
				}
			}
		});
	}

	public void initTreeGrid() {

		treeGrid = new TreeGrid();
		treeGrid.setWidth100();
		treeGrid.setHeight(400);

		treeGrid.setLoadDataOnDemand(false);

		treeGrid.setDataSource(treeDs);
		treeGrid.setAutoFetchData(true);
		treeGrid.setCanEdit(true);
		treeGrid.setCanRemoveRecords(true);
		treeGrid.setAutoSaveEdits(false);  

		TreeGridField nameField = new TreeGridField("Name", 150);
		TreeGridField idField = new TreeGridField("EmployeeId");
		TreeGridField parentIdField = new TreeGridField("ReportsTo"); 
		// Why ReportsTo field is invisible?
		TreeGridField jobField = new TreeGridField("Job", 150);
		TreeGridField employeeStatusField = new TreeGridField("EmployeeStatus",
				150);
		TreeGridField genderField = new TreeGridField("Gender");
		TreeGridField maritalStatusField = new TreeGridField("MaritalStatus");

		treeGrid.setFields(nameField, idField, parentIdField, jobField,
				employeeStatusField, genderField, maritalStatusField);

	}

	private void initInfo() {
        String ajaxDefinition =   
                        "1. Expand Charles Madigan/Tamara Kane <br>" +  
                        "2. Select Darcy Feeney <br>" +
                        "3. Click [Insert] button and add some records, enter new name <br>" +  
                        "4. Click [Save] button then [Fetch] date again <br>" +  
                        "5. All changes will lost <br>" +  
                        "6. Turn on Auto Save and try the same. You will lost data as well.";

        htmlCanvas = new Canvas();  
        htmlCanvas.setPadding(2);  
        htmlCanvas.setShowEdges(true);  
        htmlCanvas.setContents(ajaxDefinition);  
	}
	
	private void initDebugKey() {

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

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

}
