package ui.controller;

import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;

import classes.AbstractCpsObject;
import classes.CpsEdge;
import classes.CpsUpperNode;
import classes.HolonElement;
import classes.HolonObject;
import classes.HolonSwitch;
import ui.view.DefaulTable;
import ui.view.Languages;
import ui.view.PropertyTable;
import ui.view.UnitGraph;
import ui.view.UpperNodeCanvas;
import ui.model.*;
import ui.controller.*;

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

	Model model;
	Control controller;

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

	/**
	 * Update the information concerning properties of the selected CpsObject.
	 */
	public void refreshTableProperties(DefaulTable table) {

		if (model.getSelectedCpsObjects().size() == 1) {
			AbstractCpsObject tempCps = model.getSelectedCpsObject();
			if (tempCps != null && tempCps.getClass() == HolonObject.class) {
				table.removeRow(2);
				Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) tempCps).getCurrentEnergy() };
				table.insertRow(2, tempEnergy);
			}
		}
	}

	/**
	 * 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<AbstractCpsObject> objects, PropertyTable table) {
		if (objects.size() > 1) {
			for (AbstractCpsObject o : objects) {
				if (o instanceof HolonObject) {
					for (HolonElement he : ((HolonObject) o).getElements()) {
						Object[] temp = { o.getName() + ", " + o.getID(), he.getId(), he.getEleName(), he.getEnergy(),
								he.getAmount(), he.getActive() };
						table.addRow(temp);
					}
				}
			}
		} else if (objects.size() == 1) {
			AbstractCpsObject o = objects.get(0);
			if (o instanceof HolonObject) {
				for (HolonElement he : ((HolonObject) o).getElements()) {
					Object[] temp = { he.getId(), he.getEleName(), he.getEnergy(), he.getAmount(), he.getActive() };
					table.addRow(temp);
				}
			}
		}
	}

	/**
	 * 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 (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 AbstractCpsObject getActualCps() {
		AbstractCpsObject tempCps = null;
		if (model.getSelectedCpsObjects().size() == 1) {
			tempCps = model.getSelectedCpsObjects().get(0);
		} else {
			int tempID = model.getSelectedObjectID();
			// System.out.println(model.getSelectedObjectID());
			tempCps = controller.searchByID(tempID);
		}
		return tempCps;
	}

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

	public void paintProperties(AbstractCpsObject 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).getCurrentEnergy() };
				model.getPropertyTable().addRow(tempEnergy);
				model.getPropertyTable().setCellEditable(0, 1, true);
				model.getPropertyTable().setCellEditable(2, 1, false);
				model.getPropertyTable().setCellEditable(3, 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).getActiveManual() };
					model.getPropertyTable().addRow(tempActive);
					model.getPropertyTable().setCellEditable(3, 1, true);
				} else {
					Object[] tempActive = { Languages.getLanguage()[75],
							((HolonSwitch) obj).getActiveAt()[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 CpsUpperNode) {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
				Object[] numEle = { "Number of Elements", ((CpsUpperNode) obj).getNodes().size() };
				Object[] numObj = { "Number of HolonObject", ((CpsUpperNode) obj).getNumHolonObj().size() };
				Object[] numSwi = { "Number of HolonSwitch", ((CpsUpperNode) obj).getNumSwitches().size() };
				Object[] numUpp = { "Number of UpperNodes", ((CpsUpperNode) obj).getNumUpperNodes().size() };
				model.getPropertyTable().addRow(numEle);
				model.getPropertyTable().addRow(numObj);
				model.getPropertyTable().addRow(numSwi);
				model.getPropertyTable().addRow(numUpp);
			} else {
				deleteRows(model.getSingleTable());
				deleteRows(model.getMultiTable());
			}
			// For Objects the only editable cell is the name
			ArrayList<CpsEdge> tempArray = obj.getConnections();
			// If the clicked object has connections
			if (!tempArray.isEmpty()) {
				boolean first = true;
				for (CpsEdge 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.getSelectedEdge().getFlow() };
			model.getPropertyTable().addRow(tempFlow);
			// Max Capacity displayed
			Object[] tempCapacity = { Languages.getLanguage()[81], model.getSelectedEdge().getCapacity() };
			model.getPropertyTable().addRow(tempCapacity);
			// Status displayed
			Object[] tempStatus = { Languages.getLanguage()[82], model.getSelectedEdge().getState() };
			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 AbstractCpsObject getHolonObjSelected(int id) {
		AbstractCpsObject obj = null;
		for (AbstractCpsObject o : model.getSelectedCpsObjects()) {
			if (o.getID() == id) {
				obj = o;
			}
		}
		return obj;
	}

}
