package com.smartgwt.sample.showcase.client.grid.sortfilter;

import com.smartgwt.client.data.Criterion;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.TextMatchStyle;
import com.smartgwt.client.types.OperatorId;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FormItemCriterionGetter;
import com.smartgwt.client.widgets.form.SearchForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import com.smartgwt.client.widgets.form.events.ItemChangedEvent;
import com.smartgwt.client.widgets.form.events.ItemChangedHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.sample.showcase.client.PanelFactory;
import com.smartgwt.sample.showcase.client.ShowcasePanel;
import com.smartgwt.sample.showcase.client.data.WorldXmlDS;

public class TieredFilteringSample extends ShowcasePanel {

    private static final String DESCRIPTION = "<p>Sometimes you want to make common filter options really obvious "+
        "and dedicate lots of space for them. "+
        "When you do this, you don't have to sacrifice the general-purpose filtering capabilities standard to all "+
        "grids - both work together! "+
        "<P>"+
        "In the example below, there is a special filter for Northern Hemisphere vs Southern Hemisphere, which is "+
        "not a field present in the country record, and is instead implemented with AdvancedCriteria that a "+
        "sophisticated end user <i>could</i> replicate using standard filtering, but only with some effort.  "+
        "It's much more convenient as a built-in filter."+
        "<P>"+
        "Similarly, a second specialized filter for population density is based on pre-computed density groups. "+
        "A sophisticated end user could use formula fields to do the same thing, but if this is a common interface "+
        "in your application, a specialized filter interface makes sense."+
        "<P>"+
        "After playing with the specialized filter interfaces, use the header menus to pick "+
        " \"Show Filter Row\": the standard <code>FilterEditor</code> interface appears, and criteria entered here "+
        "are additive with the specialized filter. Use date range filtering on Nationhood to limit to countries "+
        "founded in the modern era."+
        "<P>"+
        "Then, choose Filter using > Advanced Filtering to see the built-in <code>filterWindow</code> interface, "+
        "allowing you to filter to show, for example, countries that are either in Europe or have a GDP above a "+
        "certain threshold or that have a small landmass but relatively high GDP."+
        "<P>"+
        "Integrating the specialized filter interface with the grid's standard filtering takes just one property "+
        "- <code>listGrid.searchForm</code> - so you no longer have to choose between simple, specialized filtering "+ 
        "and the full power of the standard, built-in filtering system.</p>";

    public static class Factory implements PanelFactory {
        private String id;

        public ShowcasePanel create() {
            TieredFilteringSample panel = new TieredFilteringSample();
            id = panel.getID();
            return panel;
        }

        public String getID() {
            return id;
        }

        public String getDescription() {
            return DESCRIPTION;
        }
    }

    public Canvas getViewPanel() {

        SearchForm specializedForm = new SearchForm();
    	specializedForm.setNumCols(4);
    	specializedForm.setWidth(800);
    	RadioGroupItem radioGroupHemisphere = new RadioGroupItem();
    	radioGroupHemisphere.setName("hemisphere");
    	radioGroupHemisphere.setTitle("Hemisphere");
    	radioGroupHemisphere.setValueMap("Any", "Northern", "Southern");
    	radioGroupHemisphere.setDefaultValue("Any");
    	radioGroupHemisphere.setVertical(false);
    	radioGroupHemisphere.setCriterionGetter(new FormItemCriterionGetter() {

			@Override
			public Criterion getCriterion(DynamicForm form, FormItem item, TextMatchStyle textMatchStyle) {
                return null;
			}

			@Override
			public Criterion getCriterion(DynamicForm form, FormItem item) {
				
				final Criterion criterionHemisphere = new Criterion();
    	    	String[] southernCountries = {"Indonesia", "Argentina", "Bolivia", "Australia", "Brasil", "Chile", "Paraguay",
    	                             "Ecuador","Mauritius", "Somalia", "Tanzania", "Zambia", 
    	                             "Peru", "Uruguay", "Angola", "Botswana", "Burundi", "Madagascar", "South Africa",
    	                             "Kenya", "Malawi", "Mozambique", "Namibia", "Nauru", "New Zeland", "Congo"};
    	    	
    	    	String value = (String)item.getValue();
    	    	if (value != null && !value.equals("Any")) {
                    if (value.equals("Northern")) {
                    	criterionHemisphere.setFieldName("countryName");
                    	criterionHemisphere.setOperator(OperatorId.NOT_IN_SET);
                    	criterionHemisphere.setAttribute("value", southernCountries);
                    } else {
                    	criterionHemisphere.setFieldName("countryName");
                    	criterionHemisphere.setOperator(OperatorId.IN_SET);
                    	criterionHemisphere.setAttribute("value", southernCountries);
                    }
                }
    	    	return criterionHemisphere;
			}
        });
    	
    	RadioGroupItem radioGroupPopulation= new RadioGroupItem(); 
    	radioGroupPopulation.setName("population");
    	radioGroupPopulation.setTitle("Population");
    	radioGroupPopulation.setValueMap("Any", "Dense", "Normal", "Sparse");
    	radioGroupPopulation.setDefaultValue("Any");
    	radioGroupPopulation.setVertical(false);
    	radioGroupPopulation.setCriterionGetter(new FormItemCriterionGetter() {

			@Override
			public Criterion getCriterion(DynamicForm form, FormItem item, TextMatchStyle textMatchStyle) {
                return null;
			}

			@Override
			public Criterion getCriterion(DynamicForm form, FormItem item) {
				
				final Criterion criterionPopulation = new Criterion();
    	    	String value = (String)item.getValue();
    	    	if (value != null && !value.equals("Any")) {
                    if (value.equals("Dense")) {
                    	criterionPopulation.setFieldName("population");
                    	criterionPopulation.setOperator(OperatorId.LESS_THAN);
                    	criterionPopulation.setAttribute("value", 1000000);
                    } else if (value.equals("Normal")) {
                    	criterionPopulation.setFieldName("population");
                    	criterionPopulation.setOperator(OperatorId.BETWEEN);
                    	criterionPopulation.setAttribute("start", 1000001);
                    	criterionPopulation.setAttribute("end", 6500000);
                    } else {
                    	criterionPopulation.setFieldName("population");
                    	criterionPopulation.setOperator(OperatorId.GREATER_THAN);
                    	criterionPopulation.setAttribute("value", 6500001);
                    }
                }
    	    	return criterionPopulation;
			}
        });
    	
    	specializedForm.setFields(radioGroupHemisphere, radioGroupPopulation);
        specializedForm.setDataSource(WorldXmlDS.getInstance());
    	specializedForm.setColWidths(120, "*", 100);
        specializedForm.addItemChangedHandler(new ItemChangedHandler() {
            @Override
            public void onItemChanged(ItemChangedEvent event) {
                specializedForm.submit();
            }
        });

    	ListGrid countryList = new ListGrid();
    	countryList.setWidth(800);
    	countryList.setHeight(224);
    	countryList.setAutoFetchData(true);
    	countryList.setCanShowFilterEditor(true);
        countryList.setDataSource(WorldXmlDS.getInstance());
    	countryList.setSearchForm(specializedForm);
        countryList.setAllowFilterOperators(true);
        countryList.setAlwaysShowOperatorIcon(true);
    	
    	ListGridField countryNameField = new ListGridField("countryName", "Country Name");
    	ListGridField continentField = new ListGridField("continent", "Continent");
    	ListGridField populationField = new ListGridField("population", "Population");
    	populationField.setType(ListGridFieldType.INTEGER);
    	ListGridField areaField = new ListGridField("area", "Area");
    	areaField.setType(ListGridFieldType.FLOAT);
    	ListGridField independenceField = new ListGridField("independence", "Independence");
    	independenceField.setType(ListGridFieldType.DATE);
    	independenceField.setWidth(150);
    	
    	countryList.setFields(countryNameField, continentField, populationField, areaField, independenceField);
    	
    	VStack vStack = new VStack();
    	vStack.setWidth100();
    	vStack.setMembersMargin(10);
    	vStack.setMembers(specializedForm, countryList);

        return vStack;
    }
    
    protected boolean isTopIntro() {
        return true;
    }

    public String getIntro() {
        return DESCRIPTION;
    }
}