package org.inria.bmajwatcher.client.ui;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.LegendPosition;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.LineChart;

/**
 * Class that builds the line charts for a given bank. 
 * 
 * @author rsabas
 *
 */
public class LineChartGenerator {

	private List<Map<String, String>> stats;

	public LineChartGenerator(List<Map<String, String>> list) {
		stats = list;
	}

	public LineChart getSizeEvolution() {
		
		return new LineChart(createData(ColumnType.NUMBER, "size", "Size"), getLineOptions("Size evolution", "Size (MB)"));
	}

	public LineChart getBandwidthEvolution() {
		
		return new LineChart(createData(ColumnType.NUMBER, "bandwidth", "Bandwidth"), getLineOptions("Bandwidth evolution", "Bandwidth (MB/s)"));
	}

	public LineChart getDurationEvolution() {

		return new LineChart(createData(ColumnType.NUMBER, "duration", "Update duration"), getLineOptions("Update duration evolution", "Duration (s)"));
	}

	public LineChart getFileTurnover() {

		return new LineChart(createData(ColumnType.NUMBER, "turnover", "Turnover"), getLineOptions("Files turnover", "Turnover %"));
	}

	public LineChart getFileCount() {
		
		return new LineChart(createData(ColumnType.NUMBER, "totalfiles", "File count"), getLineOptions("File count", null));
	}
	
	/**
	 * Creates the datatable that contains the data to be displayed in the line charts.
	 * 
	 * @param type column type (numeric, string...)
	 * @param key key in the map of the attribute to display in the chart
	 * @param columnName column name in the chart
	 * @return
	 */
	private AbstractDataTable createData(ColumnType type, String key, String columnName) {
		DataTable data = DataTable.create();
		data.addColumn(ColumnType.DATE, "Date");
		data.addColumn(type, columnName);
		data.addRows(stats.size());
		for (int i = 0; i < stats.size(); i++) {
			data.setValue(i, 0, new Date(Long.valueOf(stats.get(i).get("time"))));
			switch (type) {
			case STRING:
				data.setValue(i, 1, stats.get(i).get(key));
				break;
				
			case NUMBER:
				data.setValue(i, 1, Double.valueOf(stats.get(i).get(key)));
				break;
			}
		}
		
		return data;
	}

	
	
	private LineChart.Options getLineOptions(String title, String titleY) {

		LineChart.Options options = LineChart.Options.create();
		options.setWidth(500);
		options.setHeight(300);
		options.setTitle(title);
		if (titleY != null)
			options.setTitleY(titleY);
		options.setLegend(LegendPosition.BOTTOM);

		return options;
	}
}
