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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.jfree.chart.JFreeChart;
import org.joda.time.Interval;

import de.proveo.rts.web.config.RtsConfig;
import de.proveo.rts.web.i18n.LanguageUtil;
import de.proveo.rts.web.logicAccess.payloadData.HistoryDataAccess;
import de.proveo.rts.web.managedBeans.common.dataSelection.ReportSelectionDTOFactory;
import de.proveo.rts.web.manager.StateManager;
import de.proveo.rts.web.portlet.managedBeans.base.ChartPortletBase;
import de.proveo.rts.web.portlet.util.ChartPortletUtilities;
import de.proveo.rts.web.portlet.util.RtsPortletUtil;
import de.proveo.rts.web.util.RtsUtil;
import de.proveo.rts.web.util.charting.Charting;
import de.proveo.rts.web.util.charting.ImagemapChart;
import de.proveo.wwt.datamodel.stateModel.StateModel;
import de.proveo.wwt.logic.web.summarizedData.dto.statusPeak.StatusPeaksDTOList;

public class PeakEvaluationBean extends ChartPortletBase
{
	public Integer statusModelId;
	public Integer selectedChartSelection;
	public SelectItem[] statusModels;
	public SelectItem[] chartSelectionOptions;
//	Set<Map.Entry<Integer, String>> statusModelSet = RtsConfig.configuration.sections.gseFacts.groupDetail
//																.peakEvaluation.peakModels.status.entrySet();
	List<StateModel> stateModels = StateManager.getPeakStateModels();
																
	public PeakEvaluationBean()
	{
		super();
		fillStatusModels();
		
		if(isInitialized())
		{
			statusModelId = Integer.valueOf(RtsPortletUtil.getPreference("statusModelId", "0"));
			selectedChartSelection = Integer.valueOf(RtsPortletUtil.getPreference("selectedChartSelection", "0"));
			
			if(!RtsPortletUtil.isEditMode())
			{
				update();				
			}
		}
		else
		{
			chartWidth = 450;
			statusModelId = Integer.valueOf(RtsPortletUtil.getPreference("statusModelId", "0"));
			if(statusModelId == 0)
			{
				//TODO: Remove static satemodel declaration
				statusModelId = 2010;
			}
		}
	}
	
	public void update()
	{
		//for(Map.Entry<Integer, String> peakModel : statusModelSet)
		for(StateModel stateModel : stateModels)	
		{
			//getting the partition of the states of the selected statusModelId
			//to get the distribution of the states within the peak charts
			String states = "";
			
			if(stateModel.getId() == statusModelId.intValue())
			{
				states = stateModel.getPeakStateIds();
			
				try
				{
					Interval interval = getSelectedInterval();
					
				    String duration = String.valueOf(interval.toDurationMillis());
				    
					list = HistoryDataAccess.getStackedStatusPeakDTOList(
							ReportSelectionDTOFactory.buildUnitReportSelectionDTO(selectedUnitId, interval.getStartMillis(), interval.getEndMillis(), false),
							statusModelId, duration, states);
					
					if(isDataAvailable())
					{
						unitSelectionString = list.getName();
						
						ArrayList<Integer> stateIds = new ArrayList<Integer>();
						//List with Imagemaps
						peakCharts = new ArrayList<ImagemapChart>();
						//List with chart to save them for the maximize
						peakChartList = new ArrayList<JFreeChart>();
						
						ArrayList<Integer> modelStates = new ArrayList<Integer>();
						
						//Getting the available states for the statusModelId
						Integer[] statusArr = RtsUtil.getAvailableStateIds(statusModelId);
						for (int i = 0; i < statusArr.length; i++)
						{
							stateIds.add(statusArr[i]);
						}
						
						//possible count of charts
						String[] stateGroups = states.split(";");
						
						//looking for the selectedChartSelection to decide how many / which 
						//charts will be created
						Integer index = Integer.valueOf((int)(selectedChartSelection - statusModelId));
						if(index != 0)
						{
							String[] tempGroups = new String[1];
							tempGroups[0] = stateGroups[index - 1];
							stateGroups = tempGroups;
						}
						
						for (int i = 0; i != stateGroups.length; i++)
						{
							chart = null;
							// states for this chart
							String[] stateGroup = stateGroups[i].split(",");
							modelStates.clear();
							
							for (int j = 0; j != stateGroup.length; j++)
							{
								modelStates.add(Integer.parseInt(stateGroup[j]));
							}
		
							chart = Charting.createStackedStatusPeaksIntervalXYChart((StatusPeaksDTOList)list, 
																				modelStates, "VERTICAL", 
																				interval.getStartMillis(), 
																				interval.getEndMillis(),
																				false, false);
							if(chart != null)
							{
								ImagemapChart imagemapChart = ChartPortletUtilities.createChartUrlWithImageMap(
																					chart, chartWidth,
																					(int)(chartWidth * 0.7));
								chartUrl = RtsPortletUtil.createChartUrl(chart, chartWidth, 
																		(int)(chartWidth * 0.7), false);
								peakCharts.add(imagemapChart);
								peakChartList.add(chart);
							}
						}
					}
				}
				catch(Exception e)
				{
					errorOccured(e);
				}
			}
		}
		
	}
	
	public void save()
	{
		super.save();
		RtsPortletUtil.setPreference("statusModelId", String.valueOf(statusModelId));
		RtsPortletUtil.setPreference("selectedChartSelection", String.valueOf(selectedChartSelection));
	}
	
	//Filling the statusModels-SelectItem
	//the only values are operation and engine status
	
	private void fillStatusModels()
	{
		if (statusModels == null)
		{
			//TODO: Get States from configuration
			int[] availableStatusModels = {2010, 2050};
			statusModels = new SelectItem[availableStatusModels.length];
			for (int i = 0; i < availableStatusModels.length; i++)
			{
				statusModels[i] = new SelectItem(availableStatusModels[i], 
												 LanguageUtil.getStateModelName(availableStatusModels[i]));
			}
		}
	}
	
	//updating the chartSelectionOptions
	public void updateChartSelectionOptions()
	{
		String states = "";
		chartSelectionOptions = new SelectItem[3];
		chartSelectionOptions[0] = new SelectItem(statusModelId, 
												  RtsPortletUtil.getPortletBundleResource("portlet.edit.both"));
		for(StateModel stateModel : stateModels)
		{
			if(stateModel.getId() == statusModelId.intValue())
			{
				states = stateModel.getPeakStateIds();
			}

		}
		
		if(!states.equals(""))
		{
			String[] stateGroups = states.split(";");
			
			for(Integer i = 0; i != stateGroups.length; i++)
			{
				String[] stateIds = stateGroups[i].split(",");
				String stateName = "";
				
				for(int j = 0; j != stateIds.length; j++)
				{
					stateName = stateName.concat(LanguageUtil.getStateName(stateIds[j])).concat("/");
				}
				
				chartSelectionOptions[i + 1] = new SelectItem(statusModelId + i.intValue() + 1, stateName);
			}
		}
	}
	
	public void statusModelChanged(ValueChangeEvent event)
	{
		statusModelId = (Integer)event.getNewValue();
		RtsPortletUtil.setPreference("statusModelId", String.valueOf(statusModelId));
		updateChartSelectionOptions();
	}
	
	public void chartSelectionChanged(ValueChangeEvent event)
	{
		selectedChartSelection = (Integer)event.getNewValue();
		RtsPortletUtil.setPreference("selectedChartSelection", String.valueOf(selectedChartSelection));
	}
	
	public SelectItem[] getStatusModels()
	{
		return statusModels;
	}
	
	public Integer getStatusModelId()
	{
		return statusModelId;
	}

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

	public ArrayList<ImagemapChart> getPeakCharts()
	{
		return peakCharts;
	}
	
	public SelectItem[] getChartSelectionOptions()
	{
		if(chartSelectionOptions == null)
		{
			updateChartSelectionOptions();
		}
		
		return chartSelectionOptions;
	}

	public Integer getSelectedChartSelection()
	{
		return selectedChartSelection;
	}

	public void setSelectedChartSelection(Integer selectedChartSelection)
	{
		this.selectedChartSelection = selectedChartSelection;
	}
}
