package mobi.droidcloud.mgmt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.shared.HandlerRegistration;
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.types.Alignment;
import com.smartgwt.client.util.KeyCallback;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
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.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.MenuItemSeparator;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
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;
import com.smartgwt.client.widgets.tree.events.DataArrivedEvent;
import com.smartgwt.client.widgets.tree.events.DataArrivedHandler;
import com.smartgwt.client.widgets.tree.events.NodeContextClickEvent;
import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler;

public class JPADS implements EntryPoint {
	class MyDataArrivedHandler implements DataArrivedHandler {
		private HandlerRegistration regHandler = null;
		private TreeGrid treeGrid = null;
		
		MyDataArrivedHandler(TreeGrid tg) {
			treeGrid = tg;
		}
		
		@Override
		public void onDataArrived(DataArrivedEvent event) {
			if (regHandler != null)
				regHandler.removeHandler();
			if (treeGrid.getData().getAllNodes().length == 0) {
				Record r = new Record();
				r.setAttribute("name", "Global");
				r.setAttribute("parentDomain", (Integer)null);
				treeGrid.addData(r, new DSCallback() {
					@Override
					public void execute(DSResponse resp, Object data,
							DSRequest req) {
						if (resp.getTotalRows() != 1) {
							System.out.println("Unexpected response after adding the global node");
						}
					}
				});
			}
		}

		public void setRegistration(HandlerRegistration dahr) {
			regHandler = dahr;
		}
	}
    /** 
     * Creates a new instance of JPADS
     */
    public JPADS() {
    }

    /** 
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    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();
			}
		});

        VStack vStack = new VStack();
        vStack.setTop(50);
        vStack.setWidth("100%");
        vStack.setMembersMargin(20);
        vStack.setDefaultLayoutAlign(Alignment.CENTER);

        final TreeGrid treeGrid = new TreeGrid();
        treeGrid.setWidth("30%");
        treeGrid.setHeight(250);
        
        final DataSource domainDS = DataSource.get("domain_DataSource");
  
        TreeGridField nameField = new TreeGridField("name", "Domain Name");
        nameField.setTreeField(true);
        treeGrid.setFields(nameField);
        treeGrid.setShowConnectors(true);
		treeGrid.setCanEdit(true);
		treeGrid.setCanAcceptDroppedRecords(true);
		treeGrid.setCanReorderRecords(true);
        treeGrid.setTreeRootValue((Integer)null);
        treeGrid.setDataSource(domainDS);
        treeGrid.setAutoFetchData(true);
        MyDataArrivedHandler dah = new MyDataArrivedHandler(treeGrid);
        HandlerRegistration dahr = treeGrid.addDataArrivedHandler(dah);
        dah.setRegistration(dahr);
        final Menu contextMenu = new Menu();
        contextMenu.setTitle("Domain");
        final MenuItem delDomain = new MenuItem("Delete Domain");
        final MenuItem addDomain = new MenuItem("Add Subdomain");
        final MenuItem addRootDomain = new MenuItem("Add Root Domain");
        final MenuItemSeparator separator = new MenuItemSeparator();
        treeGrid.addNodeContextClickHandler(new NodeContextClickHandler()
        {
            public void onNodeContextClick(NodeContextClickEvent event) 
            {
            	event.cancel();
            	TreeNode n = event.getNode();
            	if (n.getAttributeAsInt("parentDomain") == null) {
            		delDomain.setTitle("Delete Root domain");
            	} else {
            		delDomain.setTitle("Delete Subdomain");
            	}
                contextMenu.setItems(addDomain, delDomain, separator, addRootDomain);
                contextMenu.showContextMenu();
            }
        });
        addDomain.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
        {
            public void onClick (MenuItemClickEvent event)
            {
                final ListGridRecord r = treeGrid.getSelectedRecord();
            	Record newDomain = new Record();
            	newDomain.setAttribute("name", "new-domain");
            	newDomain.setAttribute("parentDomain", r.getAttributeAsInt("id"));
//                treeGrid.startEditingNew(newDomain);
            	treeGrid.addData(newDomain, new DSCallback() {
					@Override
					public void execute(DSResponse response,
							Object rawData, DSRequest request) {
	                	Tree t = treeGrid.getData();
	                	if (!t.isOpen((TreeNode)r)) {
	                		// open parent node to show the new node
//	                		t.openFolder((TreeNode)r);
	                	}
					}
            	});                	
            }
        });
        addRootDomain.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
        {
            public void onClick (MenuItemClickEvent event)
            {
                final ListGridRecord r = treeGrid.getSelectedRecord();
            	// new top-level domain
				Record record = new Record();
				record.setAttribute("name", "new-domain");
				record.setAttribute("parentDomain", (Integer)null);
            	treeGrid.addData(record, new DSCallback() {
					@Override
					public void execute(DSResponse response,
							Object rawData, DSRequest request) {
					}
            	});
            }
        });
        delDomain.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler()
        {
            public void onClick (MenuItemClickEvent event)
            {
                ListGridRecord r = treeGrid.getSelectedRecord();
                if (r != null) {
                	treeGrid.removeData(r);
                }
            }
        });

        
        IButton adminButton = new IButton("Admin Console"); adminButton.addClickHandler(new ClickHandler() {
        	public void onClick(ClickEvent event) { com.smartgwtee.tools.client.SCEE.openDataSourceConsole();
        	} });
        IButton dsGeneratorButton = new IButton("DS Generator"); dsGeneratorButton.addClickHandler(new ClickHandler() {
        	public void onClick(ClickEvent event) { com.smartgwtee.tools.client.SCEE.openDataSourceGenerator();
        	} });
        vStack.addMember(treeGrid);
        vStack.addMember(dsGeneratorButton);
        vStack.draw();

    }
}
