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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.model.SelectItem;

import de.proveo.rts.web.components.picklist.PicklistItem;
import de.proveo.rts.web.i18n.LanguageUtil;
import de.proveo.rts.web.logicAccess.payloadData.CurrentDataAccess;
import de.proveo.rts.web.managedBeans.common.dataSelection.ReportSelectionDTOFactory;
import de.proveo.rts.web.portlet.managedBeans.base.ProveoPortletBase;
import de.proveo.rts.web.portlet.util.RtsPortletUtil;
import de.proveo.rts.web.util.RtsUtil;
import de.proveo.rts.web.util.time.TimePeriod;
import de.proveo.rts.web.util.time.TimePeriod.TimeFormat;
import de.proveo.wwt.datamodel.geo.GdataCache;
import de.proveo.wwt.datamodel.state.StateCache;
import de.proveo.wwt.logic.web.common.dto.UnitContainerListBase;
import de.proveo.wwt.logic.web.currentData.dto.CurrentAllDTO;

public class UnitOperationBean extends ProveoPortletBase
{
	private CurrentAllDTO dto;

	private HtmlPanelGrid grid;

	private ArrayList<PicklistItem> availableStatusModelIds = new ArrayList<PicklistItem>();

	private ArrayList<PicklistItem> assignedStatusModelIds = new ArrayList<PicklistItem>();

	private HashMap<Integer, String> allStatusModelIds = new HashMap<Integer, String>();

	private boolean viewPosition;

	private boolean viewKeepAlive;

	public UnitOperationBean()
	{
		super();

		// Retrieve all status model ids
		SelectItem[] models = RtsPortletUtil.getSessionDataBean().getStatusModels();
		allStatusModelIds = new HashMap<Integer, String>(models.length);
		for (SelectItem si : models)
			allStatusModelIds.put((Integer)si.getValue(), si.getLabel());

		assignedStatusModelIds.clear();
		if (isInitialized())
		{
			// Retrieve assigned status model ids
			String[] ids = RtsPortletUtil.getPreferences("statusModelIds");
			if (ids != null)
				for (String id : ids)
					assignedStatusModelIds.add(new PicklistItem(id, allStatusModelIds.get(Integer.parseInt(id))));

			// Get other settings
			viewPosition = Boolean.parseBoolean(RtsPortletUtil.getPreference("viewPosition", "false"));
			viewKeepAlive = Boolean.parseBoolean(RtsPortletUtil.getPreference("viewKeepAlive", "false"));

			if(!RtsPortletUtil.isEditMode())
			{
				update();
			}
		}

		// Generate list with available status model ids
		availableStatusModelIds.clear();
		Set<Entry<Integer, String>> keySet = allStatusModelIds.entrySet();
		for (Entry<Integer, String> entry : keySet)
		{
			boolean found = false;
			String key = String.valueOf(entry.getKey());
			for (PicklistItem pi : assignedStatusModelIds)
				if (pi.getValue().equals(key))
				{
					found = true;
					break;
				}
			if (!found)
				availableStatusModelIds.add(new PicklistItem(String.valueOf(entry.getKey()), entry.getValue()));
		}
		Collections.sort(availableStatusModelIds);
	}

	public HtmlPanelGrid getGrid()
	{
		grid = new HtmlPanelGrid();
		List<UIComponent> children = grid.getChildren();

		String style = "margin-right:4px";

		if (isDataAvailable())
		{
			// if (dto != null && statusModelIds != null) {
			for (int i = 0; i < assignedStatusModelIds.size(); i++)
			{
				int id = Integer.parseInt(assignedStatusModelIds.get(i).getValue());
				StateCache cscv = dto.getStates().get(id);
				if (cscv != null)
				{
					HtmlOutputText label = new HtmlOutputText();
					label.setValue(LanguageUtil.getStateModelName(id));
					label.setStyle(style);
					// label.setStyleClass("label");
					children.add(label);
					
					HtmlOutputText state = new HtmlOutputText();
					state.setValue(LanguageUtil.getStateName(cscv.getStateId()));
					children.add(state);
	
					HtmlOutputText duration = new HtmlOutputText();
					TimePeriod period = new TimePeriod(dto.getDurations().get(id), TimeFormat.SECONDS);
	
					duration.setValue(period.toString());
					children.add(duration);
				}
			}
		}

		if (viewPosition)
		{
			GdataCache cgcv = dto.getPosition();
			if (cgcv != null)
			{
				HtmlOutputText label = new HtmlOutputText();
				label.setValue("Position");
				label.setStyle(style);
				// label.setStyleClass("label");
				children.add(label);

				label = new HtmlOutputText();
				label.setValue(cgcv.getAreaId());
				children.add(label);
	
				label = new HtmlOutputText();
				TimePeriod period = new TimePeriod(dto.getCreateTime() - cgcv.getBeginTime(), 
						TimeFormat.SECONDS);
				label.setValue(period.toString());
				children.add(label);
			}
		}

		if (viewKeepAlive)
		{
			HtmlOutputText label = new HtmlOutputText();
			label.setValue("KeepAlive");
			label.setStyle(style);
			// label.setStyleClass("label");
			children.add(label);

			label = new HtmlOutputText();
			label.setValue(!dto.isTimedOut());
			children.add(label);

			label = new HtmlOutputText();
			if(dto.getKeepAliveCache() != null)
			{
				TimePeriod period = new TimePeriod(dto.getCreateTime() - dto.getKeepAliveCache().getCreateTime(), 
					TimeFormat.SECONDS);
				label.setValue(period.toString());
			}
			else
				label.setValue("------");
			children.add(label);
		}

		return grid;
	}

	public void setGrid(HtmlPanelGrid grid)
	{
		this.grid = grid;
	}

	public void save()
	{
		super.save();
		// if (selectedStateModelsChanged) not supported at this time
		{
			String[] assignedIds = new String[assignedStatusModelIds.size()];
			for (int i = 0; i < assignedStatusModelIds.size(); i++)
				assignedIds[i] = assignedStatusModelIds.get(i).getValue();
			RtsPortletUtil.setPreferences("statusModelIds", assignedIds);
		}

		RtsPortletUtil.setPreference("viewKeepAlive", String.valueOf(viewKeepAlive));
		RtsPortletUtil.setPreference("viewPosition", String.valueOf(viewPosition));
	}

	public void update()
	{
		UnitContainerListBase<CurrentAllDTO> list = CurrentDataAccess.getCurrentAllData(
				ReportSelectionDTOFactory.buildUnitReportSelectionDTO(selectedUnitId, null, null, false));
		if(list != null && !list.isEmpty())
			dto = list.get(0);
		unitSelectionString = list.getName();
	}


	public boolean isViewKeepAlive()
	{
		return viewKeepAlive;
	}

	public void setViewKeepAlive(boolean viewKeepAlive)
	{
		this.viewKeepAlive = viewKeepAlive;
	}

	public boolean isViewPosition()
	{
		return viewPosition;
	}

	public void setViewPosition(boolean viewPosition)
	{
		this.viewPosition = viewPosition;
	}

	@Override
	public boolean isDataAvailable()
	{
		return dto != null;
	}

	public ArrayList<PicklistItem> getAvailableStatusModelIds()
	{
		return availableStatusModelIds;
	}

	public void setAvailableStatusModelIds(ArrayList<PicklistItem> availableStatusModelIds)
	{
		this.availableStatusModelIds = availableStatusModelIds;
	}

	public ArrayList<PicklistItem> getAssignedStatusModelIds()
	{
		return assignedStatusModelIds;
	}

	public void setAssignedStatusModelIds(ArrayList<PicklistItem> assignedStatusModelIds)
	{
		this.assignedStatusModelIds = assignedStatusModelIds;
	}
}
