package com.bug;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.AdvancedCriteria;
import com.smartgwt.client.data.Criterion;
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.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.types.ListGridComponent;
import com.smartgwt.client.types.OperatorId;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;

public class TestBug implements EntryPoint {
    protected static String NODE = "node";
    protected static String TITLE = "title";
    protected static String DB = "db";
    protected static String _ID = "@id";
    protected static String _PID = "@p_id";
    protected static String CHILDREN = "children";
    
    private DataSource projectsData;
    private DataSource projectTreeData;
    private AdvancedCriteria courseFilter;
    private SelectItem selectedProjects;
    private SelectItem selectedCourse;
    private String project;
	
	public void onModuleLoad() {
       	project = "p0001";
        courseFilter = new AdvancedCriteria(OperatorId.OR, new Criterion[]{
                new Criterion(NODE, OperatorId.EQUALS, "unit")
        });
        createProjectsData();
	}

	public void createUI() {

        DynamicForm selectForm = new DynamicForm();
        selectForm.setWidth("100%");

        Button filterButton = new Button();
        filterButton.setVisible(false);

        ListGridField titleField = new ListGridField(TITLE, TITLE);
        ListGridField dbField = new ListGridField(DB, DB);
        dbField.setWidth(90);

        ListGrid projectsListProperties = new ListGrid();
        projectsListProperties.setShowHeaderContextMenu(false);
        projectsListProperties.setShowHeaderMenuButton(false);
        projectsListProperties.setShowFilterEditor(false);
        projectsListProperties.setShowHeader(true);
        projectsListProperties.setFilterButtonProperties(filterButton);
        projectsListProperties.setGridComponents(new Object[]{ListGridComponent.HEADER, ListGridComponent.FILTER_EDITOR, ListGridComponent.BODY});

        selectedProjects = new SelectItem();
        selectedProjects.setName("projects");
        selectedProjects.setTitle("projects");
        selectedProjects.setUseClientFiltering(false);
        selectedProjects.setWidth(400);
        selectedProjects.setValueField(DB);
        selectedProjects.setDisplayField(TITLE);
        selectedProjects.setPickListWidth(400);
        selectedProjects.setHoverWidth(400);
        selectedProjects.setPickListFields(titleField, dbField);
        selectedProjects.setMultiple(false);
        selectedProjects.setAllowEmptyValue(false);
        selectedProjects.setPickListProperties(projectsListProperties);
        selectedProjects.setOptionDataSource(projectsData);
        selectedProjects.setValue(project);
    	selectedProjects.setWidth(350);
    	selectedProjects.addChangedHandler(new ChangedHandler() {
            @Override
            public void onChanged(ChangedEvent event) {
            	project = (String) event.getValue();
            	loadProject();

            }
        });

    	JavaScriptObject object = JavaScriptObject.createObject();
        JSOHelper.setAttribute(object, "fireItemClickForFolders", true);

        Tree courseTree = new Tree();
        courseTree.setIdField(_ID);
        courseTree.setParentIdField(_PID);

        TreeGrid courseListProperties = new TreeGrid(object);
        courseListProperties.setKeepParentsOnFilter(true);
//        courseListProperties.setDataProperties(courseTree);

        selectedCourse = new SelectItem();
        selectedCourse.setName("selectedCourse");
        selectedCourse.setWidth(350);
        selectedCourse.setPickListWidth(400);
        selectedCourse.setHoverWidth(400);
        selectedCourse.setDataSetType("tree");
        selectedCourse.setPickListProperties(courseListProperties);
        selectedCourse.setTitle("course item");
        selectedCourse.setValueField(_ID);
        selectedCourse.setDisplayField(TITLE);
        selectedCourse.setMultiple(false);
        selectedCourse.setAllowEmptyValue(false);
        selectedCourse.setAddUnknownValues(false);
        selectedCourse.setAutoFetchData(false);
        selectedCourse.setOptionDataSource(projectTreeData);
        selectedCourse.setPickListCriteria(courseFilter);
        selectedCourse.setAutoOpenTree("all");
        selectedCourse.setEmptyDisplayValue("select any Course Item");

        selectForm.setItems(selectedProjects, selectedCourse);
        RootPanel.get("content").add(selectForm);

    }

	private void createProjectsData() {
        projectsData = new DataSource();
        projectsData.setID("projectsData");
        projectsData.setClientOnly(true);

        DataSourceTextField projectTitleData = new DataSourceTextField(TITLE);
        DataSourceTextField projectDBData = new DataSourceTextField(DB);
        projectDBData.setPrimaryKey(true);

        projectsData.setFields(projectTitleData, projectDBData);

        String urlProjects = "projects.json";
        projectsData.setDataURL(urlProjects);

        projectsData.fetchData(null, new DSCallback() {
            public void execute(DSResponse response, Object rawData, DSRequest request) {
            	loadProject();
            }
        });
    }
    private void loadProject() {
        final String DSID = project + "_Data";
    	if(projectTreeData !=null) {
    		projectTreeData.destroy();
    	}
        DataSourceTextField idField = new DataSourceTextField(_ID);
        idField.setPrimaryKey(true);
        idField.setRequired(true);
        idField.setHidden(true);

        DataSourceTextField pidField = new DataSourceTextField(_PID);
        pidField.setRequired(true);  
        pidField.setHidden(true);

        DataSourceTextField titleField = new DataSourceTextField(TITLE);
        DataSourceTextField nodeData = new DataSourceTextField(NODE);

        DataSourceField childrenData = new DataSourceField(CHILDREN, FieldType.ANY);
        childrenData.setChildrenProperty(true);
        childrenData.setHidden(true);

    	projectTreeData = new DataSource() {
            @Override
            protected void transformResponse(DSResponse response, DSRequest request, Object data) {
                Record[] childs = response.getData();
                setProjectNodesProperties(childs);
                super.transformResponse(response, request, data);
            }
        };
        projectTreeData.setID(DSID);
        projectTreeData.setFields(idField, pidField, titleField, nodeData, childrenData);
        projectTreeData.setChildrenField(CHILDREN);
        projectTreeData.setAutoCacheAllData(true);
        projectTreeData.setCacheAllData(true);
        projectTreeData.setClientOnly(true);
        
        String url  = "projectTree" + "_" + project + ".json";
        projectTreeData.setDataURL(url);

        if(selectedCourse == null) {
        	projectTreeData.fetchData(null, new DSCallback() {
				@Override
				public void execute(DSResponse dsResponse, Object data, DSRequest dsRequest) {
		            createUI();
                	selectFirstCourse();
				}
			});
        } else {
            selectedCourse.setOptionDataSource(projectTreeData);
            selectedCourse.fetchData(new DSCallback() {
    			@Override
    			public void execute(DSResponse dsResponse, Object data, DSRequest dsRequest) {
                	selectFirstCourse();
    			};
    		});
        }
    }
    private void setProjectNodesProperties(Record[] records) {
        for (Record record : records) {
          	record.setAttribute("id", record.getAttribute(_ID));
          	record.setAttribute("parentId", record.getAttribute(_PID));
            Record[] childs = record.getAttributeAsRecordArray(CHILDREN);
            if(childs != null && childs.length > 0) {
            	setProjectNodesProperties(childs);
            } else {
            	record.setAttribute("isFolder", false);
            }
        }
    }
    
    private void selectFirstCourse() {
    	Record[] records = projectsData.getCacheData();
    	String course = null;
    	for(Record record:records) {
    		if(record.getAttribute(DB).contains(project)) {
    			course = record.getAttribute("firstCourse");
    			break;
    		}
    	}
    	if(course != null) {
    		selectedCourse.setDefaultValue(course);
    	}
    }
}
