package ui.controller;

import classes.*;
import classes.comparator.elementComparator.ElemCompOnEleName;
import classes.comparator.elementComparator.ElemCompOnEnergy;
import classes.comparator.elementComparator.ElemCompOnId;
import classes.comparator.elementComparator.ElemCompOnIsActivated;
import classes.comparator.elementComparator.ElemCompOnObj;
import classes.comparator.elementComparator.ElemCompOnQuantity;
import classes.comparator.elementComparator.ElementComparator;
import ui.model.DecoratedGroupNode;
import ui.model.DecoratedHolonObject.HolonObjectState;
import ui.model.Model;
import ui.view.DefaulTable;
import ui.view.Languages;
import ui.view.PropertyTable;
import ui.view.GroupNodeCanvas;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * This class is for all update methods and more ;)
 * 
 * @author Gruppe14
 *
 */
public class UpdateController {

	Model model;
	Control controller;
	private int sortBy;

	public UpdateController(Model model, Control control) {
		this.model = model;
		this.controller = control;
		sortBy= 1;
	}

	/**
	 * Update the information concerning properties of the selected CpsObject.
	 */
	public void refreshTableProperties(DefaulTable table) {
		if (model.getSelectedCpsObjects().size() == 1) {
			AbstractCanvasObject tempCps = model.getSelectedCpsObjects().get(0);
			if (tempCps != null && tempCps.getClass() == HolonObject.class) {
				if (table.getRowCount() != 0) {
					table.removeRow(2);
					Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) tempCps).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
					table.insertRow(2, tempEnergy);
					table.removeRow(3);
					Object[] tempFlex = { "Flexibility", ((HolonObject) tempCps).getTotalFlex() };
					table.insertRow(3, tempFlex);
				}
			}
		}
	}

	    
	/**
	 * Add the Information of the given ArrayList in the HolonElement Model as
	 * Name,Energy and Amount.
	 * 
	 * @param objects
	 *            ArrayList to be displayed
	 */
	public void fillElementTable(ArrayList<AbstractCanvasObject> objects, PropertyTable table) {
		LinkedList<HolonElement> elemList = new LinkedList<HolonElement>();
		
		if (objects.size() > 1) {
			for (AbstractCanvasObject o : objects) {
				if (o instanceof HolonObject) {
					for (HolonElement he : ((HolonObject) o).getElements()) {
						he.setObjName(o.getName() + ", " + o.getId());
						elemList.add(he);
						elemList=sortElemList(elemList);
					}
				}
			}
			for (HolonElement e1 : elemList) {
				Object[] temp2 = { e1.getObjName(), e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
						controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(e1), e1.getAmount(), e1.isActive()};
				table.addRow(temp2);
			}

		} else if (objects.size() == 1) {
			AbstractCanvasObject o = objects.get(0);
			if (o instanceof HolonObject) {
				for (HolonElement he : ((HolonObject) o).getElements()) {
					elemList.add(he);
					elemList=sortElemList(elemList);
				}
				
				for (HolonElement e1 : elemList) {
					Object[] temp2 = { e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
							controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(e1), e1.getAmount(), e1.isActive()};
					table.addRow(temp2);
				}
			}
		}
	}
	
	/**
	 * @param elemList - HolonElement-List (unsorted)
	 * @return sorted HolonElement-List! 
	 */
	public LinkedList<HolonElement> sortElemList(LinkedList<HolonElement> elemList) {
		switch(sortBy) {
		case 0://"Object": 
			elemList.sort(new ElemCompOnObj());
			break;
		case 1://ID
			elemList.sort(new ElemCompOnId());
			break;
		case 2://"Device": 
			elemList.sort(new ElemCompOnEleName());
			break;
		case 3://"Energy": 
			elemList.sort(new ElemCompOnEnergy());
			break;
		case 4://"Flexible Energy Available": 
			elemList.sort(null);
			break;
		case 5://"Quantity": 
			elemList.sort(new ElemCompOnQuantity());
			break;
		case 6://"Activated": 
			elemList.sort(new ElemCompOnIsActivated());
			break;
		case 7://"Flexible": 
			elemList.sort(null);
			break;
		default: 
			elemList.sort(new ElemCompOnId());
			break;
		}
		return elemList;
	};

	/**
	 * Update the HolonElement Table, that means erase all rows and add the new
	 * rows with new data.
	 */
	public void refreshTableHolonElement(PropertyTable multiTable, PropertyTable singleTable) {
		// Update of the Information about the HolonElements - only for
		// HolonObjects
		if(multiTable == null || singleTable == null ) return;
		if (model.getSelectedCpsObjects().size() > 1) {
			deleteRows(multiTable);
			fillElementTable(model.getSelectedCpsObjects(), multiTable);
			multiTable.fireTableDataChanged();
		} else if (model.getSelectedCpsObjects().size() == 1) {
			deleteRows(singleTable);
			fillElementTable(model.getSelectedCpsObjects(), singleTable);
			singleTable.fireTableDataChanged();
		}
	}

	/**
	 * Erase all information of the HolonElement Model.
	 * 
	 * @param t
	 *            the Table
	 */
	public void deleteRows(PropertyTable t) {
		if (t.getRowCount() > 0) {
			for (int i = t.getRowCount() - 1; i > -1; i--) {
				t.removeRow(i);
			}
		}
	}

	/**
	 * Search for clicked HolonObject through the mouse's y-Coord.
	 * 
	 * @param yValue
	 *            the Y Coordination
	 * @return clicked HolonObject
	 */
	public HolonObject getHolonObj(int yValue, PropertyTable table) {
		final int yTemp = (int) Math.floor(yValue / 16);
		HolonObject obtTemp = null;
		String temp = table.getValueAt(yTemp, 0).toString();
		int idTemp = Integer.parseInt(temp.split(", ")[1]);
		obtTemp = (HolonObject) controller.searchByID(idTemp);
		return obtTemp;
	}

	/**
	 * Search for actual selected HolonElement.
	 * 
	 * @param obj
	 *            selected HolonObject, if obj==null means multi-selection
	 *            active
	 * @param yValue
	 *            Y-Coord in the HolonElementsTable
	 * @param toMultiHash
	 *            0 means no MultiSelection, 1 means MultiSelection without
	 *            Control, 2 means MultiSelection with Control
	 * @return the selected HolonElement
	 */
	public HolonElement getActualHolonElement(HolonObject obj, int yValue, int toMultiHash,
			ArrayList<PropertyTable> tables) {
		final int yTemp = (int) Math.floor(yValue / 16);
		int rowsTotal = 0;
		// Filter for search --> single and multi selection
		if (obj == null) {
			rowsTotal = tables.get(1).getRowCount();
		} else {
			rowsTotal = tables.get(0).getRowCount();
		}
		// search for the clicked HolonObject and HolonElement --> in the
		// HolonElementTable
		HolonObject obtTemp = null;
		HolonElement toReturnEle = null;
		int id = 0;
		if (rowsTotal != 0 && rowsTotal > yTemp) {
			// Multi-Selection search
			if (obj == null) {
				String tempStringObj = tables.get(1).getValueAt(yTemp, 0).toString();
				int idTempObj = Integer.parseInt(tempStringObj.split(", ")[1]);
				if (model.getSelectedCpsObjects() != null) {
					obtTemp = (HolonObject) getHolonObjSelected(idTempObj);
				}
				id = Integer.parseInt(tables.get(1).getValueAt(yTemp, 1).toString());
				ArrayList<HolonElement> eleTemp = new ArrayList<HolonElement>();
				if (model.getEleToDelete().containsKey(idTempObj) && toMultiHash == 2) {
					eleTemp = model.getEleToDelete().get(idTempObj);
					if (!eleTemp.contains(obtTemp.searchElementById(id))) {
						eleTemp.add(obtTemp.searchElementById(id));
						model.getEleToDelete().replace(idTempObj, eleTemp);
					}
				} else if (toMultiHash == 2) {
					eleTemp.add(obtTemp.searchElementById(id));
					model.getEleToDelete().put(idTempObj, eleTemp);
				} else if (toMultiHash == 1) {
					model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
					eleTemp.add(obtTemp.searchElementById(id));
					model.getEleToDelete().put(idTempObj, eleTemp);
				} else if (toMultiHash == 0) {
					toReturnEle = obtTemp.searchElementById(id);
				}
			} // Single-Selection search
			else {
				model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
				id = Integer.parseInt(tables.get(0).getValueAt(yTemp, 0).toString());
				toReturnEle = obj.searchElementById(id);
			}
			model.setSelectedHolonElement(toReturnEle);
			return toReturnEle;
		} // If no HolonObject selected
		else {
			model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
			model.setSelectedHolonElement(null);
			return null;
		}
	}

	/**
	 * Getter for selected CpsObject.
	 * 
	 * @return selected CpsObject
	 */
	public AbstractCanvasObject getActualCps() {
        AbstractCanvasObject tempCps;
        if (model.getSelectedCpsObjects().size() == 1) {
			tempCps = model.getSelectedCpsObjects().get(0);
		} else {
			int tempID = model.getSelectedObjectID();
			tempCps = controller.searchByID(tempID);
		}
		return tempCps;
	}

	/**
	 * Getter for selected CpsObject.
	 * 
	 * @return selected CpsObject
	 */
	public AbstractCanvasObject getActualCpsUpperNode(GroupNodeCanvas canvas) {
		int tempID = model.getSelectedObjectID();
		AbstractCanvasObject tempCps = controller.searchByIDUpperNode(tempID, canvas.upperNode);
		return tempCps;
	}

	public void paintProperties(AbstractCanvasObject obj) {
		if (obj != null) {
			// Name of the CpsObject
			Object[] tempName = { Languages.getLanguage()[72], obj.getName() };
			model.getPropertyTable().addRow(tempName);
			// Id of the CpsObject
			Object[] tempId = { "ID", obj.getId() };
			model.getPropertyTable().addRow(tempId);
			// For HolonObjects the Total Energy (production or
			// consumption) is calculated
			if (obj instanceof HolonObject) {
				refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
				Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) obj).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
				Object[] tempFlex = { "Flexibility", ((HolonObject) obj).getTotalFlex() };
				model.getPropertyTable().addRow(tempEnergy);
				model.getPropertyTable().addRow(tempFlex);
				model.getPropertyTable().setCellEditable(0, 1, false);
				model.getPropertyTable().setCellEditable(2, 1, false);
				model.getPropertyTable().setCellEditable(3, 1, false);
				model.getPropertyTable().setCellEditable(4, 1, false);
			} // For HolonSwitches is showed the actual status (active
				// or inactive)
			else if (obj instanceof HolonSwitch) {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
				Object[] tempMode = { Languages.getLanguage()[74], ((HolonSwitch) obj).getManualMode() };
				model.getPropertyTable().addRow(tempMode);
				if (((HolonSwitch) obj).getManualMode()) {
					Object[] tempActive = { Languages.getLanguage()[75], ((HolonSwitch) obj).getManualState() };
					model.getPropertyTable().addRow(tempActive);
					model.getPropertyTable().setCellEditable(3, 1, true);
				} else {
					Object[] tempActive = { Languages.getLanguage()[75],
							((HolonSwitch) obj).getState(model.getCurIteration()) };
					model.getPropertyTable().addRow(tempActive);
					model.getPropertyTable().setCellEditable(3, 1, false);
				}
				// unitGraph.repaintWithNewSwitch((HolonSwitch) obj);
				// elementGraph.setText(obj.getName());
				model.getPropertyTable().setCellEditable(0, 1, true);
				model.getPropertyTable().setCellEditable(2, 1, true);
			} else if (obj instanceof GroupNode) {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
				//short fix please make me new
				DecoratedGroupNode dGroupNode = controller.getSimManager().getVisualRepresentationalState(model.getCurIteration()).getCreatedGroupNodes().get((GroupNode) obj);
				Object[] info = { "Statistics:", "" };
				
				Object[] numEle = { "Number of Objects (total)", ((GroupNode) obj).getNodes().size() };
				Object[] numObj = { "Number of HolonObjects", ((GroupNode) obj).getNumHolonObj().size() };
				Object[] numSwi = { "Number of HolonSwitches", ((GroupNode) obj).getNumSwitches().size() };
				Object[] numUpp = { "Number of GroupNodes", ((GroupNode) obj).getNumUpperNodes().size() };
				model.getPropertyTable().addRow(info);
				model.getPropertyTable().addRow(numEle);
				model.getPropertyTable().addRow(numObj);
				model.getPropertyTable().addRow(numSwi);
				model.getPropertyTable().addRow(numUpp);
				if(dGroupNode != null) {
					int numerator, denominator;
					Object[] title = { "HolonObject Statistics:", "" };
					
					denominator	= dGroupNode.getAmountOfConsumer() + dGroupNode.getAmountOfSupplier() + dGroupNode.getAmountOfPassiv();
					
					numerator = dGroupNode.getAmountOfSupplier();
					Object[] producer = { "Producer:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};					
					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
					Object[] notSupplied = { "UnSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
					Object[] partiallySupplied = { "PartriallySupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
					Object[] supplied = { "Supplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
					Object[] overSupplied = { "OverSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					numerator = dGroupNode.getAmountOfPassiv();
					Object[] passiv = { "Passiv(%):",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					
					Object[] nothing= {"", ""};
					numerator = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
					denominator = dGroupNode.getAmountOfElemntsFromHolonObjects();
					Object[] aktiv = { "Active HolonElements:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
					float consumption = dGroupNode.getConsumptionFromConsumer();
					float production = dGroupNode.getProductionFromSupplier();
					Object[] consumptionObj = { "Total Consumption:",  consumption};
					Object[] productionObj = { "Total Production:",  production};
					Object[] difference = { "Difference:", production - consumption};
					
					
					model.getPropertyTable().addRow(title);
					model.getPropertyTable().addRow(producer);
					model.getPropertyTable().addRow(notSupplied);
					model.getPropertyTable().addRow(partiallySupplied);
					model.getPropertyTable().addRow(supplied);
					model.getPropertyTable().addRow(overSupplied);
					model.getPropertyTable().addRow(passiv);
					model.getPropertyTable().addRow(nothing);
					model.getPropertyTable().addRow(aktiv);
					model.getPropertyTable().addRow(nothing);
					model.getPropertyTable().addRow(consumptionObj);
					model.getPropertyTable().addRow(productionObj);
					model.getPropertyTable().addRow(difference);
				}
				
			} else if (obj instanceof HolonBattery) {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
				Object[] numInRatio = {"InRatio:", ((HolonBattery)obj).getInRatio() };
				Object[] numOutRatio = {"OutRatio:", ((HolonBattery)obj).getOutRatio() };
				Object[] numSOC_Capasity = {"State of charge:", Float.toString(((HolonBattery)obj).getStateOfChargeAtTimeStep(model.getCurIteration()-1)) + "/" + Float.toString(((HolonBattery)obj).getCapacity()) };
				model.getPropertyTable().addRow(numInRatio);
				model.getPropertyTable().addRow(numOutRatio);
				model.getPropertyTable().addRow(numSOC_Capasity);
				
				model.getPropertyTable().setCellEditable(0, 1, true);
				model.getPropertyTable().setCellEditable(2, 1, true);
				model.getPropertyTable().setCellEditable(3, 1, true);
			}else {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
			}
			// For Objects the only editable cell is the name
			ArrayList<Edge> tempArray = obj.getConnections();
			// If the clicked object has connections
			if (!tempArray.isEmpty()) {
				boolean first = true;
				for (Edge temp2 : tempArray) {
					if (first) {
						first = false;
						if (obj.getId() != temp2.getA().getId()) {
							Object[] tempConnection = { obj.getName() + Languages.getLanguage()[76],
									temp2.getA().getName() + Languages.getLanguage()[77] + temp2.getA().getId() };
							model.getPropertyTable().addRow(tempConnection);
						} else {
							Object[] tempConnection = { obj.getName() + Languages.getLanguage()[76],
									temp2.getB().getName() + Languages.getLanguage()[77] + temp2.getB().getId() };
							model.getPropertyTable().addRow(tempConnection);
						}
					} else {
						if (obj.getId() != temp2.getA().getId()) {
							Object[] tempConnection = { "",
									temp2.getA().getName() + Languages.getLanguage()[77] + temp2.getA().getId() };
							model.getPropertyTable().addRow(tempConnection);
						} else {
							Object[] tempConnection = { "",
									temp2.getB().getName() + Languages.getLanguage()[77] + temp2.getB().getId() };
							model.getPropertyTable().addRow(tempConnection);
						}
					}
				}
			}
		} // If the clicked Object is an edge
		else if (model.getSelectedEdge() != null) {
			// Name displayed
			Object[] tempName = { Languages.getLanguage()[72],
					Languages.getLanguage()[78] + model.getSelectedEdge().getA().getName() + Languages.getLanguage()[79]
							+ model.getSelectedEdge().getB().getName() };
			model.getPropertyTable().addRow(tempName);
			// Current Flow displayed
			Object[] tempFlow = { Languages.getLanguage()[80], "" };
			model.getPropertyTable().addRow(tempFlow);
			// Max Capacity displayed
			Object[] tempCapacity = { Languages.getLanguage()[81], model.getSelectedEdge().getCapacity() };
			model.getPropertyTable().addRow(tempCapacity);
			// Status displayed
            Object[] tempStatus = {"Length", model.getSelectedEdge().getLength() };
            model.getPropertyTable().addRow(tempStatus);
            // For edges, the only possible editable cell is the max
			// flow
			model.getPropertyTable().setCellEditable(0, 1, false);
			model.getPropertyTable().setCellEditable(2, 1, true);
			model.getPropertyTable().setCellEditable(3, 1, true);
		} else if (getActualCps() == null) {
			deleteRows(model.getSingleTable());
			deleteRows(model.getMultiTable());
		}
		// Update of the HolonElementTable (Single- or Multi-Selection)
		if (model.getSelectedCpsObjects().size() > 1) {
			model.getTableHolonElement().setModel(model.getMultiTable());
		} else if (model.getSelectedCpsObjects().size() == 1) {
			model.getTableHolonElement().setModel(model.getSingleTable());
		}
	}

	public AbstractCanvasObject getHolonObjSelected(int id) {
		AbstractCanvasObject obj = null;
		for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
			if (o.getId() == id) {
				obj = o;
				break;
			}
		}
		return obj;
	}

	/**
	 * fills the table when HolonCanvas is open
	 * 
	 * @param id
	 *            ID of the selected HolonBody
	 */
	public void paintHolonBody(int id) {
		if (id != -1) {
			
			ArrayList<SubNet> subs = controller.getSimManager().getSubNets();
			if (!subs.isEmpty()) {
				SubNet sub = subs.get(id);
				Object[] tempId = { "ID", id };
				model.getPropertyTable().addRow(tempId);
				Object[] tempObj = { "Nr. of Objects", sub.getObjects().size() };
				model.getPropertyTable().addRow(tempObj);
				Object[] tempEdg = { "Nr. of Edges", sub.getEdges().size() };
				model.getPropertyTable().addRow(tempEdg);
				Object[] tempSwi = { "Nr. of Switches", sub.getSwitches().size() };
				model.getPropertyTable().addRow(tempSwi);
				Object[] tempProd = { "Total Production",
						"" + controller.getTotalProduction(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
				model.getPropertyTable().addRow(tempProd);
				Object[] tempCons = { "Total Consumption",
						"" + controller.getTotalConsumption(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
				model.getPropertyTable().addRow(tempCons);
				Object[] tempEle = { "Nr. of Elements",
						"" + controller.getTotalElements(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
				model.getPropertyTable().addRow(tempEle);
				Object[] tempProds = { "Nr. of Producers",
						"" + controller.getTotalProducers(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
				model.getPropertyTable().addRow(tempProds);
				Object[] tempAct = { "Nr. of active Elements",
						"" + controller.getActiveElements(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
				model.getPropertyTable().addRow(tempAct);
			}
		}
	}

	/**
	 * 
	 * @return id of column that should be sorted
	 */
	public int getSortBy() {
		return sortBy;
	}

	/**
	 * sets the column id that should be sorted
	 * @param column
	 */
	public void setSortBy(int column) {
		/**
		 * if there is no "Object" column, assume coloumn 0 is
		 */
		if(model.getTableHolonElement().getColumnCount()==7)
			this.sortBy = column+1;
		else
			this.sortBy = column;
	}
}
