package de.proveo.rts.web.portlet.managedBeans.statusCharts;

import java.util.ArrayList;

import javax.faces.model.SelectItem;

import org.joda.time.Interval;

import de.proveo.rts.web.logicAccess.payloadData.HistoryDataAccess;
import de.proveo.rts.web.managedBeans.common.dataSelection.ReportSelectionDTOFactory;
import de.proveo.rts.web.portlet.managedBeans.base.ChartPortletBase;
import de.proveo.rts.web.portlet.util.RtsPortletUtil;
import de.proveo.rts.web.util.charting.Charting;
import de.proveo.rts.web.util.charting.plot.StatusStackedBarPlot;
import de.proveo.wwt.logic.web.historyData.dto.StateDTOList;

public class StatusBarChartBean extends ChartPortletBase
{

	private Integer statusModelId;

	private boolean summarized;

	public StatusBarChartBean()
	{
		super();

		if (isInitialized())
		{
			statusModelId = Integer.valueOf(RtsPortletUtil.getPreference("statusModelId", "0"));

			summarized = Boolean.valueOf(RtsPortletUtil.getPreference("summarized", "false"));

			if(!RtsPortletUtil.isEditMode())
			{
				update();				
			}
		}
		else
		{
			chartWidth = 450;
		}
	}

	public void update()
	{
		try
		{
			Interval interval = getSelectedInterval();

			list = HistoryDataAccess.getStateData(
					ReportSelectionDTOFactory.buildUnitReportSelectionDTO(selectedUnitId, interval.getStartMillis(), interval.getEndMillis(), false),
					statusModelId,
					false);

			if (isDataAvailable())
			{
				unitSelectionString = list.getName();

				if (!summarized)
					chart = Charting.createStateStackedBarChartVertical((StateDTOList)list, null, interval);
				else
					chart = Charting.createStateStackedSummarziedBarChartVertical((StateDTOList)list, null, interval);

				if (!showLegend)
					chart.setSubtitles(new ArrayList());

				StatusStackedBarPlot plot = (StatusStackedBarPlot)chart.getPlot();

				chartUrl = RtsPortletUtil.createChartUrl(chart, chartWidth, plot.calculateChartHeight(height), false);
			}

		}
		catch (Exception e)
		{
			errorOccured(e);
		}
	}

	public void save()
	{
		super.save();
		RtsPortletUtil.setPreference("statusModelId", String.valueOf(statusModelId));
		RtsPortletUtil.setPreference("summarized", String.valueOf(summarized));
	}

	public Integer getStatusModelId()
	{
		return statusModelId;
	}

	public void setStatusModelId(Integer statusModelId)
	{
		this.statusModelId = statusModelId;

	}

	public boolean isSummarized()
	{
		return summarized;
	}

	public void setSummarized(boolean summarized)
	{
		this.summarized = summarized;
	}
	
	public SelectItem[] getStatusModels()
	{
		return RtsPortletUtil.getStatusModels();
	}

}
