package br.com.dti.testesmartgwt.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ChartType;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.chart.FacetChart;
import com.smartgwt.client.widgets.cube.Facet;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class TesteSmartGWTEntryPoint implements EntryPoint 
{
	private VLayout rootLayout;
	private List<Canvas> memberList = new ArrayList<Canvas>();
	
	@Override
	public void onModuleLoad()
	{
		try
		{
			rootLayout = new VLayout();
			rootLayout.setWidth("98,5%");
			rootLayout.setHeight("97%");
			RootPanel.get().add(rootLayout);
			buildLayout();
		}
		catch (Exception e)
		{
		}
	}

	private void buildLayout()
	{
		List<Integer> list = new ArrayList<Integer>();
		list.add(3);
		list.add(4);
		list.add(5);
		load(list);
	}
	
	private void load(List<Integer> pLista)
	{
		clear();
		for (Integer i : pLista)
			memberList.add(getChartLayout(i));
		rootLayout.addMembers(memberList.toArray(new Canvas[] {}));
	}
	
	private void clear()
	{
		rootLayout.removeMembers(memberList.toArray(new Canvas[] {}));
		memberList.clear();
	}
	
	private HLayout getChartLayout(final Integer parameter)
	{
		FacetChart chart = new FacetChart();
		chart.setFacets(new Facet("entity", " "), new Facet("class", "Class"));
		chart.setValueProperty("occurrenceNumber");
		chart.setChartType(ChartType.BAR);
		chart.setHeight(74);
		chart.setWidth(150);
		chart.setAlign(Alignment.CENTER);
		chart.setShowDataValues(false);
		chart.setShowTitle(false);
		chart.setShowDataAxisLabel(false);
		chart.setShowValueAxisLabel(false);
		chart.setShowLegend(false);
        chart.setData(getRecords());
        
		HLayout hlayout = new HLayout();
		hlayout.addMember(chart);
		hlayout.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				List<Integer> list = new ArrayList<Integer>();
				for (int i = 1; i <= parameter; i++)
					list.add(i+1);
				load(list);
			}
		});
		return hlayout;
	}
	
	private Record[] getRecords()
	{
		List<Record> list = new ArrayList<Record>();
		list.add(getRecord("Class 1", 3));
		list.add(getRecord("Class 2", 5));
		list.add(getRecord("Class 3", 1));
		return list.toArray(new Record[] {});
	}
	
	private Record getRecord(String clazz, Integer occurrenceNumber)
	{
		Record record = new Record();
		record.setAttribute("class", clazz);
		record.setAttribute("occurrenceNumber", occurrenceNumber);
		record.setAttribute("entity", " ");
		return record;
    }
}
