package org.example.client;

import java.util.HashMap;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.Autofit;
import com.smartgwt.client.types.DragDataAction;
import com.smartgwt.client.types.HeaderControls;
import com.smartgwt.client.util.KeyCallback;
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.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tree.TreeGridField;

public class SmartButton implements EntryPoint {

	protected static int usersGroupsRelGridCounter = 0;
	protected static int userWindowCounter = 0;
	private static int usersDepartmentRelGridCounter = 0;

	public void onModuleLoad() {
		
		if (!GWT.isScript()) { 
		    KeyIdentifier debugKey = new KeyIdentifier(); 
		    debugKey.setCtrlKey(true); 
		    debugKey.setKeyName("D"); 
		    Page.registerKey(debugKey, new KeyCallback() { 
		        public void execute(String keyName) { 
		            SC.showConsole(); 
		        }
		    });
		}
		final Canvas canvas = new Canvas();

		canvas.setHeight100();
		canvas.setWidth100();

		IButton createNewUserWindowButton = new IButton("Click ME!");
		createNewUserWindowButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Window usersWindow = new SmartWindow();
				usersWindow.setHeaderControls(HeaderControls.HEADER_LABEL);

				usersWindow.setTitle("UsersWindow");

				usersWindow.setWidth(500);
				usersWindow.setHeight(300);

				usersWindow.setCanDragReposition(true);
				usersWindow.setCanDragResize(true);

				final ListGrid usersGrid = new ListGrid(){

					@Override  
					protected Canvas getExpansionComponent(final ListGridRecord userRecord) {  
						
						VLayout layout = new VLayout();

						final ListGrid usersGroupsRelGrid = new ListGrid();
						
						usersGroupsRelGrid.setDropTypes("groups");

						String autoID = usersGroupsRelGrid.getID();
						usersGroupsRelGridCounter++;
						usersGroupsRelGrid.setID("usersGroupsRelGrid"+usersGroupsRelGridCounter+autoID);
						usersGroupsRelGrid.setAddOperation("usersGroupsRelGrid"+usersGroupsRelGridCounter+autoID);

						usersGroupsRelGrid.setPreventDuplicates(true);
						usersGroupsRelGrid.setWidth100();
						usersGroupsRelGrid.setCellHeight(40);
						usersGroupsRelGrid.setAutoFitData(Autofit.VERTICAL);
						usersGroupsRelGrid.setShowAllRecords(true);
						usersGroupsRelGrid.setDrawAheadRatio(4);

						usersGroupsRelGrid.setDataSource(UserGroupsRelDataSource.getInstance());

						usersGroupsRelGrid.fetchRelatedData(userRecord, UsersDataSource.getInstance());
						usersGroupsRelGrid.setAddDropValues(true);
						HashMap<String, String> userDropValues = new HashMap<String, String>();
						userDropValues.put("userID", userRecord.getAttribute("u_id"));
//						userDropValues.put("ug_id", userRecord.getAttribute("u_id"));
						usersGroupsRelGrid.setDropValues(userDropValues);

//						Criteria c = new Criteria();
//						c.addCriteria("userID", userRecord.getAttribute("u_id"));
//						usersGroupsRelGrid.setCriteria(c);

						usersGroupsRelGrid.setCanDrag(false);
						usersGroupsRelGrid.setCanDragRecordsOut(false);  
						usersGroupsRelGrid.setCanEdit(false);
						usersGroupsRelGrid.setCanAcceptDroppedRecords(true);

						usersGroupsRelGrid.setShowHeader(true);

						TreeGridField userName = new TreeGridField("userID", "Last Name");
						userName.setOptionDataSource(UsersDataSource.getInstance());
						userName.setValueField("u_id");
						userName.setDisplayField("lastName");
//						userName.setName("userID");
//						userName.setTitle("Last Name");
//						userName.setAutoFetchDisplayMap(true);

						TreeGridField groupName = new TreeGridField("groupID", "Group Name");
						groupName.setOptionDataSource(GroupsDataSource.getInstance());
						groupName.setValueField("g_id");
						groupName.setDisplayField("groupName");
//						groupName.setName("groupID");
//						groupName.setTitle("Group Name");
//						groupName.setAutoFetchDisplayMap(true);
						
						

						usersGroupsRelGrid.setFields(userName, groupName);
						usersGroupsRelGrid.setShowHeader(true);
						
						layout.addMember(usersGroupsRelGrid);
						
						//Add a second grid showing the UserDepartmentRelation here
						
						final ListGrid usersDepartmentRelGrid = new ListGrid();
						
						usersDepartmentRelGrid.setDropTypes("departments");
						autoID = usersDepartmentRelGrid.getID();
						usersDepartmentRelGridCounter++;
						usersDepartmentRelGrid.setID("usersDepartmentRelGrid"+usersDepartmentRelGridCounter+autoID);
						usersDepartmentRelGrid.setAddOperation("usersDepartmentRelGrid"+usersDepartmentRelGridCounter+autoID);

						usersDepartmentRelGrid.setPreventDuplicates(true);
						usersDepartmentRelGrid.setWidth100();
						usersDepartmentRelGrid.setCellHeight(40);
						usersDepartmentRelGrid.setAutoFitData(Autofit.VERTICAL);
						usersDepartmentRelGrid.setShowAllRecords(true);
						usersDepartmentRelGrid.setDrawAheadRatio(4);

						usersDepartmentRelGrid.setDataSource(UserDepartmentRelDataSource.getInstance());

						usersDepartmentRelGrid.fetchRelatedData(userRecord, UsersDataSource.getInstance());
						usersDepartmentRelGrid.setAddDropValues(true);
						HashMap<String, String> departmentDropValues = new HashMap<String, String>();
						departmentDropValues.put("userID", userRecord.getAttribute("u_id"));
//						departmentDropValues.put("ud_id", userRecord.getAttribute("u_id"));
						usersDepartmentRelGrid.setDropValues(departmentDropValues);

//						Criteria c = new Criteria();
//						c.addCriteria("userID", userRecord.getAttribute("u_id"));
//						usersGroupsRelGrid.setCriteria(c);

						usersDepartmentRelGrid.setCanDrag(false);
						usersDepartmentRelGrid.setCanDragRecordsOut(false);  
						usersDepartmentRelGrid.setCanEdit(false);
						usersDepartmentRelGrid.setCanAcceptDroppedRecords(true);

						usersDepartmentRelGrid.setShowHeader(true);

						userName = new TreeGridField("userID", "Last Name");
						userName.setOptionDataSource(UsersDataSource.getInstance());
						userName.setValueField("u_id");
						userName.setDisplayField("lastName");
//						userName.setName("userID");
//						userName.setTitle("Last Name");
//						userName.setAutoFetchDisplayMap(true);

						TreeGridField departmentName = new TreeGridField("departmentID", "Department Name");
						departmentName.setOptionDataSource(DepartmentsDataSource.getInstance());
						departmentName.setValueField("d_id");
						departmentName.setDisplayField("departmentName");
//						departmentName.setName("groupID");
//						departmentName.setTitle("Group Name");
//						departmentName.setAutoFetchDisplayMap(true);
						
						//Add a second grid showing the UserDepartmentRelation here

						usersDepartmentRelGrid.setFields(userName, departmentName);
						usersDepartmentRelGrid.setShowHeader(true);
						
						layout.addMember(usersDepartmentRelGrid);

//						usersGroupsRelGrid.fetchData(c);

						return layout;
					}
				};

				SmartButton.userWindowCounter++;
				usersGrid.setID("usersGroupsGrid"+userWindowCounter);
				usersGrid.setAddOperation("usersGroupsGrid"+userWindowCounter);

				usersGrid.setWidth100();
				usersGrid.setHeight100();

				ListGridField lastName = new ListGridField("lastName", "Last Name");
				ListGridField firstName = new ListGridField("firstName","First Name");

				usersGrid.setFields(lastName, firstName);
				usersGrid.setCanExpandRecords(true);

				UsersDataSource ds = UsersDataSource.getInstance();
				usersGrid.setDataSource(ds);
				usersGrid.fetchData();
				
				
				
				
				
				usersWindow.addItem(usersGrid);
				canvas.addChild(usersWindow);
			}
		});

		//Groups window
		Window groupsWindow = new SmartWindow();
		groupsWindow.setHeaderControls(HeaderControls.HEADER_LABEL);
		groupsWindow.setTitle("GroupsWindow");

		groupsWindow.setWidth(500);
		groupsWindow.setHeight(300);

		groupsWindow.setCanDragReposition(true);
		groupsWindow.setCanDragResize(true);

		final ListGrid groupsGrid = new ListGrid();
		
		groupsGrid.setDragType("groups");

		groupsGrid.setWidth100();
		groupsGrid.setHeight100();

		ListGridField groupName = new ListGridField("groupName", "Name");
		ListGridField groupPermission = new ListGridField("groupPermission","Permission");

		groupsGrid.setFields(groupName, groupPermission);
		groupsGrid.setShowRecordComponents(true);
		groupsGrid.setShowRecordComponentsByCell(true);
		groupsGrid.setDragDataAction(DragDataAction.COPY);

		groupsGrid.setCanDragRecordsOut(true);

		GroupsDataSource groupsDataSource = GroupsDataSource.getInstance();
		groupsGrid.setDataSource(groupsDataSource);
		groupsGrid.fetchData();

		groupsWindow.addItem(groupsGrid);
		
		//Groups window
		Window departmentsWindow = new SmartWindow();
		departmentsWindow.setHeaderControls(HeaderControls.HEADER_LABEL);
		departmentsWindow.setTitle("DepartmentWindow");

		departmentsWindow.setWidth(500);
		departmentsWindow.setHeight(300);

		departmentsWindow.setCanDragReposition(true);
		departmentsWindow.setCanDragResize(true);

		final ListGrid departmentsGrid = new ListGrid();
		
		departmentsGrid.setDragType("departments");

		departmentsGrid.setWidth100();
		departmentsGrid.setHeight100();

		ListGridField departmentName = new ListGridField("departmentName", "Name");
		ListGridField location = new ListGridField("location","Location");

		departmentsGrid.setFields(departmentName, location);
		departmentsGrid.setShowRecordComponents(true);
		departmentsGrid.setShowRecordComponentsByCell(true);
		departmentsGrid.setDragDataAction(DragDataAction.COPY);

		departmentsGrid.setCanDragRecordsOut(true);

		DepartmentsDataSource departmentsDataSource = DepartmentsDataSource.getInstance();
		departmentsGrid.setDataSource(departmentsDataSource);
		departmentsGrid.fetchData();

		departmentsWindow.addItem(departmentsGrid);

		canvas.addChild(departmentsWindow);
		canvas.addChild(groupsWindow);
		canvas.addChild(createNewUserWindowButton);

		canvas.draw();
	}


	public static class UsersDataSource extends DataSource {

		private static UsersDataSource instance;

		public static UsersDataSource getInstance() {  
			if (instance == null) {  
				instance = new UsersDataSource("users");  
			}
			return instance;  
		}

		public UsersDataSource(String dsID){
			setID(dsID);
			setClientOnly(true);
			DataSourceField id = new DataSourceIntegerField("u_id");
			id.setHidden(true);
			id.setRequired(false);
			id.setPrimaryKey(true);
			addField(id);
			DataSourceField field = new DataSourceTextField("lastName");
			addField(field);
			field = new DataSourceTextField("firstName");
			addField(field);

			createRecord(1,"Smith", "John");
			createRecord(2,"Smith", "Dave");
			createRecord(3,"Smith", "Pat");
			createRecord(4,"Jones", "Jim");
			createRecord(5,"Jones", "Mary");
			createRecord(6,"Johnson", "Paul");
			createRecord(7,"Brown", "Ed");
		}

		private void createRecord(int id, String last, String first){
			ListGridRecord record = new ListGridRecord();
			record.setAttribute("u_id", id);
			record.setAttribute("lastName", last);
			record.setAttribute("firstName", first);
			addData(record);
		}
	}

	public static class GroupsDataSource extends DataSource {

		private static GroupsDataSource instance;

		public static GroupsDataSource getInstance() {  
			if (instance == null) {  
				instance = new GroupsDataSource("groups");  
			}
			return instance;  
		}

		public GroupsDataSource(String dsID){
			setID(dsID);
			setClientOnly(true);
			DataSourceField id = new DataSourceIntegerField("g_id");
			id.setHidden(true);
			id.setRequired(false);
			id.setPrimaryKey(true);
			addField(id);
			DataSourceField field = new DataSourceTextField("groupName");
			addField(field);
			field = new DataSourceTextField("groupPermission");
			addField(field);

			createRecord(1,"Admin", "777");
			createRecord(2,"User", "750");
			createRecord(3,"Observer", "333");
		}

		private void createRecord(int id, String groupName, String groupPermission){
			ListGridRecord record = new ListGridRecord();
			record.setAttribute("g_id", id);
			record.setAttribute("groupName", groupName);
			record.setAttribute("groupPermission", groupPermission);
			addData(record);
		}
	}
	
		public static class DepartmentsDataSource extends DataSource {

		private static DepartmentsDataSource instance;

		public static DepartmentsDataSource getInstance() {  
			if (instance == null) {  
				instance = new DepartmentsDataSource("departments");  
			}
			return instance;  
		}

		public DepartmentsDataSource(String dsID){
			setID(dsID);
			setClientOnly(true);
			DataSourceField id = new DataSourceIntegerField("d_id");
			id.setHidden(true);
			id.setPrimaryKey(true);
			addField(id);
			DataSourceField field = new DataSourceTextField("departmentName", "Department Name", 128);
			addField(field);
			field = new DataSourceTextField("location", "Location", 128);
			addField(field);

			createRecord(1,"CTO", "NY");
			createRecord(2,"HR", "Chicago");
			createRecord(3,"CRM", "Springfield");
		}

		private void createRecord(int id, String departmentName, String departmentLocation){
			ListGridRecord record = new ListGridRecord();
			record.setAttribute("d_id", id);
			record.setAttribute("departmentName", departmentName);
			record.setAttribute("location", departmentLocation);
			addData(record);
		}
	}

	public static class UserGroupsRelDataSource extends DataSource {

		private static UserGroupsRelDataSource instance;

		public static UserGroupsRelDataSource getInstance() {  
			if (instance == null) {  
				instance = new UserGroupsRelDataSource("userGroupsRel");  
			}
			return instance;  
		}

		public UserGroupsRelDataSource(String dsID){
			setID(dsID);
			setClientOnly(true);
			DataSourceField id = new DataSourceIntegerField("ug_id");
			id.setHidden(true);
			id.setPrimaryKey(true);
			id.setRequired(false);
			addField(id);
			DataSourceField field = new DataSourceTextField("userID");
			field.setForeignKey("users.u_id");
			addField(field);
			field = new DataSourceTextField("groupID");
			field.setForeignKey("groups.g_id");
			addField(field);
		}
	}
	
	public static class UserDepartmentRelDataSource extends DataSource {

		private static UserDepartmentRelDataSource instance;

		public static UserDepartmentRelDataSource getInstance() {  
			if (instance == null) {  
				instance = new UserDepartmentRelDataSource("userDepartmentsRel");  
			}
			return instance;  
		}

		public UserDepartmentRelDataSource(String dsID){
			setID(dsID);
			setClientOnly(true);
			DataSourceField id = new DataSourceIntegerField("ud_id");
			id.setHidden(true);
			id.setPrimaryKey(true);
			id.setRequired(true);
			addField(id);
			DataSourceField field = new DataSourceTextField("userID");
			field.setForeignKey("users.u_id");
			addField(field);
			field = new DataSourceTextField("departmentID");
			field.setForeignKey("departments.d_id");
			addField(field);
		}
	}
}