package ui.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import classes.AbstractCpsObject;
import classes.CpsEdge;
import classes.CpsUpperNode;
import classes.Position;
import ui.model.Model;
import ui.view.UpperNodeCanvas;

public class NodeController {

	private Model model;
	private CanvasController cvs;
	private MultiPurposeController mpC;

	public NodeController(Model model, CanvasController cvs, MultiPurposeController mpC) {
		// TODO Auto-generated constructor stub
		this.model = model;
		this.cvs = cvs;
		this.mpC = mpC;
	}

	/**
	 * Add a CpsUpperNode into Canvas
	 * 
	 * @param nodeName
	 * @param upperNode
	 */
	public void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {

		CpsUpperNode node = new CpsUpperNode(nodeName);
		node.setPosition(calculatePos(toGroup));
		makeAdjacent(node, upperNode, toGroup);
		makeNodeOfNodes(node, upperNode, toGroup);
		backupOldEdges(node, upperNode);
		if (upperNode == null)
			cvs.addNewObject(node);
		else
			addObjectInUpperNode(node, upperNode);

	}

	/**
	 * Delete a CpsUpperNode from the Canvas
	 * 
	 * @param node
	 * @param upperNode
	 */
	public void undoUpperNode(CpsUpperNode node, CpsUpperNode upperNode) {
		restoreOldEdges(node, upperNode);
		unmakeNodesOfNodes(node, upperNode);
		unmakeAdjacent(node, upperNode);
		if (upperNode == null)
			cvs.deleteObjectOnCanvas(node);
		else
			deleteObjectInUpperNode(node, upperNode);
	}

	/**
	 * Put selected Nodes inside the Upper Node
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void makeNodeOfNodes(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {

		ArrayList<AbstractCpsObject> nodes = node.getNodes();
		ArrayList<CpsEdge> toDelete = new ArrayList<>();

		// Put all selected Nodes into the Upper Node
		for (Iterator<AbstractCpsObject> it = toGroup.iterator(); it.hasNext();) {

			// füge Neue Objecte in Neuen Node hinzu
			AbstractCpsObject obj = it.next();
			// POSITION MUSS NEU GEMACHT WERDEN FÜR OBJECTS IN NODE OF NODE
			// obj.setPosition((obj.getPosition().x + node.getPosition().x) / 2,
			// (obj.getPosition().y + node.getPosition().y) / 2);
			addObjectInUpperNode(obj, node);
		}

		// Füge die Edges die Alle Objekte vorher verbunden hat in neuen Node
		for (Iterator<CpsEdge> it = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())
				.iterator(); it.hasNext();) {

			CpsEdge edge = it.next();

			// kopiere edge in UpperNode
			if (nodes.contains(edge.getA()) && nodes.contains(edge.getB())) {
				toDelete.add(edge);
				addEdge(edge, node);
			}

		}

		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).removeAll(toDelete);
		// Lösche dann die Edges aus der nächst höheren schicht
		for (AbstractCpsObject abs : toGroup) {
			if (upperNode == null)
				removeForNodeOfNode(abs, null);
			else
				removeForNodeOfNode(abs, upperNode);
		}

	}

	/**
	 * Transfer all relevant data from Node into the next higher layer of Node
	 * (upperNode)
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void unmakeNodesOfNodes(CpsUpperNode node, CpsUpperNode upperNode) {
		// TODO Auto-generated method stub
		// add all nodes into upperNode

		for (CpsEdge edge : node.getConnections()) {
			if (edge.getA().equals(node))
				edge.getB().getConnections().remove(edge);
			if (edge.getB().equals(node))
				edge.getA().getConnections().remove(edge);
		}

		(upperNode == null ? model.getObjectsOnCanvas() : upperNode.getNodes()).addAll(node.getNodes());
		// change the indices accordingly the higher layer
		mpC.adjustIdx(mpC.getHighestIdx((upperNode == null ? model.getCvsObjIdx() : upperNode.getNodesIdx())),
				node.getNodesIdx());
		// add all indices of nodes into upperNode
		(upperNode == null ? model.getCvsObjIdx() : upperNode.getNodesIdx()).putAll(node.getNodesIdx());
		// add all Edges of node into upperNode
		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).addAll(node.getNodeEdges());
	}

	/**
	 * Look for adjacent Nodes connected with the new CpsUpperNode and make
	 * Connections
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void makeAdjacent(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {

		ArrayList<AbstractCpsObject> adj = new ArrayList<>();
		ArrayList<Float> maxCapacity = new ArrayList<>();

		ArrayList<CpsEdge> oldEdges = node.getOldEdges();
		ArrayList<CpsEdge> toDelete = new ArrayList<>();

		// für alle Edges auf dem Canvas
		for (Iterator<CpsEdge> it = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())
				.iterator(); it.hasNext();) {

			CpsEdge edge = it.next();

			// wenn ausgewählte Objekte in edge und andere auserhalb
			if (toGroup.contains(edge.getA()) && !toGroup.contains(edge.getB())) {
				// und wenn in der adj noch nicht vorhanden und füg
				if (!adj.contains(edge.getB())) {
					adj.add(edge.getB());
					maxCapacity.add(edge.getCapacity());
				}
				// wenn vorhanden teste maxCapacity
				else if (maxCapacity.get(adj.indexOf(edge.getB())) < edge.getCapacity()) {
					maxCapacity.set(adj.indexOf(edge.getB()), edge.getCapacity());
				}
				// speichere alte edge
				oldEdges.add(edge);
				toDelete.add(edge);

			}

			// Analog
			else if (!toGroup.contains(edge.getA()) && toGroup.contains(edge.getB())) {
				if (!adj.contains(edge.getA())) {
					adj.add(edge.getA());
					maxCapacity.add(edge.getCapacity());
				} else if (maxCapacity.get(adj.indexOf(edge.getA())) < edge.getCapacity()) {
					maxCapacity.set(adj.indexOf(edge.getA()), edge.getCapacity());

				}
				oldEdges.add(edge);
				toDelete.add(edge);
			}
		}

		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).removeAll(toDelete);

		// für alle objekte in adjazenzliste mach
		for (AbstractCpsObject cps : adj) {
			CpsEdge newEdge = new CpsEdge(cps, node, maxCapacity.get(adj.indexOf(cps)));
			// !! Eventuell noch bei getConnections() hinzufügem
			// node.getConnections().add(newEdge);
			if (upperNode == null)
				cvs.addEdgeOnCanvas(newEdge);
			else
				upperNode.getNodeEdges().add(newEdge);

		}
	}

	/**
	 * Restore the Old Connections from the adjacent Object
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void unmakeAdjacent(CpsUpperNode node, CpsUpperNode upperNode) {
		// TODO Auto-generated method stub
		ArrayList<CpsEdge> toDelete = new ArrayList<>();
		ArrayList<CpsEdge> lostEdges = new ArrayList<>();
		ArrayList<AbstractCpsObject> found = (upperNode == null ? model.getObjectsOnCanvas() : upperNode.getNodes());
		ArrayList<AbstractCpsObject> lostChildren = new ArrayList<>();

		// für jede Edge aus upperNode die Node enthält tu sie in toDelete
		for (Iterator<CpsEdge> it = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())
				.iterator(); it.hasNext();) {

			CpsEdge edge = it.next();
			if (edge.getA().equals(node) || edge.getB().equals(node))
				toDelete.add(edge);

		}
		// mark all object that arent in the restored oldEdges
		for (CpsEdge edge : node.getOldEdges()) {
			if (node.getNodes().contains(edge.getA()) && !found.contains(edge.getB()) && !lostEdges.contains(edge)) {
				lostChildren.add(edge.getA());
				lostEdges.add(edge);
				// edge.getB().getConnections().remove(edge);
			}

			else if (node.getNodes().contains(edge.getB()) && !found.contains(edge.getA())
					&& !lostEdges.contains(edge)) {
				lostChildren.add(edge.getB());
				lostEdges.add(edge);
				// edge.getA().getConnections().remove(edge);
			}
		}
		node.getOldEdges().removeAll(lostEdges);

		// LOST = DIE IN NODE SIND, TOSEARCH = IHRE PARTNER DIE IN ANDEREN NODES
		// SIND

		for (CpsEdge edge : lostEdges) {
			AbstractCpsObject toSearch = null;
			AbstractCpsObject lost = null;

			if (lostChildren.contains(edge.getA())) {
				toSearch = edge.getB();
				lost = edge.getA();
			} else if (lostChildren.contains(edge.getB())) {
				toSearch = edge.getA();
				lost = edge.getB();
			}
			if (toSearch instanceof CpsUpperNode) {
				for (CpsEdge e : lost.getConnections()) {
					if ((found.contains(e.getA()) || found.contains(e.getB())) && !node.getOldEdges().contains(e))
						node.getOldEdges().add(e);
				}
			} else
				outerLoop: for (AbstractCpsObject cps : found) {
					if (!cps.equals(node) && !lostChildren.contains(cps))
						if (backtrackLostChild(cps, toSearch, lost)) {

							for (CpsEdge f : node.getOldEdges())
								if ((f.getA().equals(cps) && f.getB().equals(toSearch))
										|| (f.getB().equals(cps) && f.getA().equals(toSearch)))
									continue outerLoop;

							if (!lookforDuplicates(cps, lost, node.getOldEdges())) {
								
								CpsEdge temp = new CpsEdge(cps, lost, edge.getCapacity());
								node.getOldEdges().add(temp);

								//break;
							}

						}
				}

		}

		// lösch alle Edges die in toDelete sind und wiederherstell alte Edges
		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).removeAll(toDelete);
		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).addAll(node.getOldEdges());

	}

	private boolean lookforDuplicates(AbstractCpsObject a, AbstractCpsObject b, ArrayList<CpsEdge> list) {
		for (CpsEdge cpsEdge : list) {
			if ((a.equals(cpsEdge.getA()) && b.equals(cpsEdge.getB()))
					|| (b.equals(cpsEdge.getA()) && a.equals(cpsEdge.getB())))
				return true;
		}
		return false;
	}

	/**
	 * Backups Old Edges into next lower layer in Current UpperNode anymore
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void backupOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {

		ArrayList<CpsEdge> backup = new ArrayList<>();
		ArrayList<AbstractCpsObject> adj = new ArrayList<>();
		ArrayList<Float> maxCapacity = new ArrayList<>();

		// wenn upperNode in UpperNode erzeugt wird
		if (upperNode != null) {
			// für alle oldEdges die die zu gruppierenden nodes enthält werden
			// in die neuen upperNOde verschoben
			for (CpsEdge edge : upperNode.getOldEdges()) {
				if (!upperNode.getNodes().contains(edge.getA()) && !upperNode.getNodes().contains(edge.getB()))
					backup.add(edge);
			}
			// hier wird verschoben
			node.getOldEdges().addAll(backup);

			// neue adjazent muss hergestellt werden in den alten oldEdges
			for (CpsEdge edge : upperNode.getOldEdges()) {

				if (node.getNodes().contains(edge.getA()))
					if (!adj.contains(edge.getB())) {
						adj.add(edge.getB());
						maxCapacity.add(edge.getCapacity());
					} else if (maxCapacity.get(adj.indexOf(edge.getB())) < edge.getCapacity()) {
						maxCapacity.set(adj.indexOf(edge.getB()), edge.getCapacity());

					}
				if (node.getNodes().contains(edge.getB()))
					if (!adj.contains(edge.getA())) {
						adj.add(edge.getA());
						maxCapacity.add(edge.getCapacity());
					} else if (maxCapacity.get(adj.indexOf(edge.getA())) < edge.getCapacity()) {
						maxCapacity.set(adj.indexOf(edge.getA()), edge.getCapacity());

					}
			}
			// alle übertragenen Edges werden gelöscht
			upperNode.getOldEdges().removeAll(backup);
			// neue edges werden erzeugt
			for (AbstractCpsObject cps : adj)
				upperNode.getOldEdges().add(new CpsEdge(cps, node, maxCapacity.get(adj.indexOf(cps))));

		}
	}

	/**
	 * Restore Old Edges into next higher layer of UpperNode
	 * 
	 * @param node
	 * @param upperNode
	 */
	private void restoreOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {

		ArrayList<CpsEdge> toDelete = new ArrayList<>();

		if (upperNode != null) {
			for (CpsEdge edge : node.getOldEdges()) {
				// wenn upperNode weder A oder B von von den OldEdges enthält
				if (!upperNode.getNodes().contains(edge.getA()) && !upperNode.getNodes().contains(edge.getB()))
					// Übertrage die OldEdges eine Schicht höher
					toDelete.add(edge);
			}
			// übertrage sie hier
			upperNode.getOldEdges().addAll(toDelete);
			// lösch sie aus den zu löschenden node, da sonst durch unmake
			// Adjacent probleme auftauchen
			node.getOldEdges().removeAll(toDelete);
			toDelete.clear();
			// lösche alle OldEdges aus der höheren schicht die zu den zu
			// löschenden Node vorher führten
			for (CpsEdge edge : upperNode.getOldEdges()) {
				if (edge.getA().equals(node) || edge.getB().equals(node))
					toDelete.add(edge);
			}
			upperNode.getOldEdges().removeAll(toDelete);
		}

	}

	/**
	 * Calculate new Position of the Upper Node
	 * 
	 * @return
	 */
	private Position calculatePos(ArrayList<AbstractCpsObject> toGroup) {

		Position pos = new Position(0, 0);

		// sum(x0 .. xn) / numOfPos, y analog
		for (AbstractCpsObject abs : toGroup) {
			pos.x += abs.getPosition().x;
			pos.y += abs.getPosition().y;
		}
		pos.x /= toGroup.size();
		pos.y /= toGroup.size();

		return pos;
	}

	private void removeForNodeOfNode(AbstractCpsObject obj, CpsUpperNode upperNode) {

		mpC.decIdx(obj.getID(), (upperNode == null ? model.getCvsObjIdx() : upperNode.getNodesIdx()));
		(upperNode == null ? model.getCvsObjIdx() : upperNode.getNodesIdx()).remove(obj.getID());
		(upperNode == null ? model.getObjectsOnCanvas() : upperNode.getNodes()).remove(obj);
	}

	/**
	 * Search Lost Nodes by Backtracking
	 * 
	 * @param lost
	 * @param object
	 * @return
	 */
	private boolean backtrackLostChild(AbstractCpsObject object, AbstractCpsObject find, AbstractCpsObject lost) {
		if (!(object instanceof CpsUpperNode)) {
			for (CpsEdge edge : object.getConnections()) {
				if (edge.getA().equals(find) && edge.getB().equals(lost)
						|| edge.getA().equals(lost) && edge.getB().equals(find))
					return true;
			}
			return false;
		} else {
			for (AbstractCpsObject cps : ((CpsUpperNode) object).getNodes()) {
				if (backtrackLostChild(cps, find, lost))
					return true;
			}
			return false;
		}
	}

	/**
	 * Add a Object into a CpsUpperNode
	 * 
	 * @param object
	 * @param upperNode
	 */
	public void addObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
		object.setSav("UPPER" + upperNode.getID());
		upperNode.getNodesIdx().put(object.getID(), upperNode.getNodes().size());
		upperNode.getNodes().add(object);
	}

	/**
	 * Delete a AbstactCpsObject from CPSUpperNode
	 * 
	 * @param object
	 * @param upperNode
	 */
	public void deleteObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
		CpsEdge e = null;
		for (AbstractCpsObject cps : upperNode.getNodes()) {
			for (CpsEdge p : cps.getConnections()) {
				if (p.getA() == object || p.getB() == object) {
					e = p;
				}
			}
			if (!model.getClipboradObjects().contains(cps) && !(cps instanceof CpsUpperNode)) {
				cps.getConnectedTo().remove(e);
			}
			upperNode.getNodeEdges().remove(e);
		}
		mpC.decIdx(object.getID(), upperNode.getNodesIdx());
		upperNode.getNodesIdx().remove(object.getID());
		upperNode.getNodes().remove(object);
	}

	/**
	 * Add Edge in UpperNode
	 * 
	 * @param edge
	 * @param upperNode
	 */
	public void addEdge(CpsEdge edge, CpsUpperNode upperNode) {
		upperNode.getNodeEdges().add(edge);
	}

	/**
	 * Delete Edge in UpperNode
	 * 
	 * @param edge
	 * @param upperNode
	 */
	public void deleteEdge(CpsEdge edge, CpsUpperNode upperNode) {
		edge.getA().getConnections().remove(edge);
		edge.getB().getConnections().remove(edge);
		upperNode.getNodeEdges().remove(edge);
		if (edge.getA() instanceof CpsUpperNode || edge.getB() instanceof CpsUpperNode)
			cvs.handleUpperNodes(edge);
	}

	/**
	 * Adds a Edge into Connections of AbstactCpsObjects
	 * 
	 * @param a
	 * @param b
	 */
	public void connectNodes(CpsEdge edge, CpsUpperNode upperNode) {
		// mache hier Connections in A und B rein
		// mache diese Edge auch in OldEdges rein des aktuellen CpsUpperNodes
		upperNode.getOldEdges().add(edge);
	}

	public void disconnectNodes(CpsEdge edge, CpsUpperNode upperNode) {
		edge.getA().getConnections().remove(edge);
		edge.getB().getConnections().remove(edge);
		if (upperNode != null)
			upperNode.getOldEdges().remove(edge);
	}

}
