/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 *
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.topology.movement;

import java.util.*;

import de.tud.kom.p2psim.api.network.SimNetInterface;
import de.tud.kom.p2psim.api.topology.movement.MovementModel;
import de.tud.kom.p2psim.api.topology.movement.SimLocationActuator;
import de.tud.kom.p2psim.impl.network.routed.RoutedNetLayer;
import de.tud.kom.p2psim.impl.topology.PositionVector;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci.TraciSimulationController;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.xml.XMLSimulationController;
import de.tud.kom.p2psim.impl.vehicular.trafficlights.DefaultTrafficLightInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.Event;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.TrafficLightController;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.trafficlights.TrafficLight;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.trafficlights.TrafficLightInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;

public class RSUMovementModel implements MovementModel, EventHandler {

	private final List<SimLocationActuator> components;
	private final Map<String, SimLocationActuator> idComponentMatcher;
	private final Queue<SimLocationActuator> freeComponents;
	private final Map<INodeID, String> hostTrafficLightIdMatching;
	private final Map<INodeID, Integer> hostIntersectionMatching;

	private final String sumoExe;
	private final String sumoConfigFile;
	private final String sumoTripOutputFile;

	private final String sumoIntersections;

	private final int offsetX;
	private final int offsetY;
	private final int width;
	private final int height;

	private final long timestepConversion = Time.SECOND;
	private long timeBetweenMoveOperations;

	private boolean initialized = false;
	private boolean _reuseComponents = false;

	private TrafficLightController _controller;
	private SimulationSetupExtractor _extractor;


	private List<Location> _intersections;
	private int _currentIndex = 0;

	private static final Location DEFAULT_LOCATION = new PositionVector(Double.NaN, Double.NaN);

	@XMLConfigurableConstructor({ "timeBetweenMoveOperations", "sumoExe", "sumoConfigFile", "sumoTripOutputFile", "offsetX", "offsetY", "width", "height" })
	public RSUMovementModel(long timeBetweenMoveOperations, String sumoExe, String sumoConfigFile,  String sumoTripOutputFile, String offsetX, String offsetY, String width, String height) {
		this.components = new LinkedList<>();
		this.idComponentMatcher = new HashMap<>();
		this.freeComponents = new LinkedList<>();
		this.hostTrafficLightIdMatching = new HashMap<>();
		this.hostIntersectionMatching =  new HashMap<>();

		this.timeBetweenMoveOperations = timeBetweenMoveOperations;

		this.sumoExe = sumoExe;
		this.sumoConfigFile = sumoConfigFile;
		this.sumoTripOutputFile = sumoTripOutputFile;

		this.sumoIntersections = null;

		this.offsetX = Integer.parseInt(offsetX);
		this.offsetY = Integer.parseInt(offsetY);
		this.width = Integer.parseInt(width);
		this.height = Integer.parseInt(height);
	}

	@XMLConfigurableConstructor({ "timeBetweenMoveOperations", "sumoIntersections", "offsetX", "offsetY", "width", "height" })
	public RSUMovementModel(long timeBetweenMoveOperations, String sumoIntersections,  String offsetX, String offsetY, String width, String height) {
		this.components = new LinkedList<>();
		this.idComponentMatcher = new HashMap<>();
		this.freeComponents = new LinkedList<>();
		this.hostTrafficLightIdMatching = new HashMap<>();
		this.hostIntersectionMatching =  new HashMap<>();

		this.timeBetweenMoveOperations = timeBetweenMoveOperations;
		this.sumoIntersections = sumoIntersections;

		this.sumoExe = null;
		this.sumoConfigFile = null;
		this.sumoTripOutputFile = null;

		this.offsetX = Integer.parseInt(offsetX);
		this.offsetY = Integer.parseInt(offsetY);
		this.width = Integer.parseInt(width);
		this.height = Integer.parseInt(height);
	}

	@Override
	public final void addComponent(SimLocationActuator comp) {
		components.add(comp);
		freeComponents.add(comp);
	}

	@Override
	public void setTimeBetweenMoveOperations(long time) {
		//Do nothing, only used for placement of RSU
	}

	@Override
	public synchronized void placeComponent(SimLocationActuator actuator) {
		if (!initialized) {
			initializeModel();
			initialized = true;
		}

		if (_currentIndex < _intersections.size()) {
			// Initial placement
			Location intersection = _intersections.get(_currentIndex);
			actuator.updateCurrentLocation(new PositionVector(intersection.getLongitude(), intersection.getLatitude()));

			hostIntersectionMatching.put(actuator.getHost().getId(), _currentIndex);

			_currentIndex++;

			//Put interfaces online
		} else {
			actuator.updateCurrentLocation(DEFAULT_LOCATION);
		}
	}

	/**
	 * Initializes the movement model by executing BonnMotion and parsing the
	 * resulting movement trace.
	 */
	protected void initializeModel() {
		if (!initialized) {

			Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);

			if (this.sumoExe != null) {
				_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, null);
				_controller.init();
				_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
				_intersections = _controller.getAllIntersections(true);
			} else {
				_controller = new XMLSimulationController(null, sumoIntersections);
				_controller.init();
				_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
				_intersections = _controller.getAllIntersections(true);
			}
		}

		//		System.out.println("Require " + _intersections.size() + " RSUs");
	}

	@Override
	public void eventOccurred(Object content, int type) {
		//Call everyTrafficLight!
		long currentTime = Time.getCurrentTime() / timestepConversion;

		while (_controller.getStep() - _controller.getStart() < currentTime) {
			if (!_controller.nextStep()) {
				return;
			}
		}

		//Assumption grid, Intersections and traffic lights are the same number
		//Fix for robust usage
		List<Location> intersections = _controller.getAllIntersections(true);
		List<TrafficLight> trafficLights = _controller.getAllTrafficLights();

		for (int i = 0 ; i < trafficLights.size() ; i++) {
			TrafficLight trafficLight = trafficLights.get(i);
			Location trafficLightLocation = intersections.get(i);

			if (trafficLightLocation == null) {
				trafficLights.remove(i--);
				continue;
			}

			SimLocationActuator component = requestSimActuator(trafficLight.getTrafficLightId());
			try {
				RoutedNetLayer routedNetLayer = component.getHost().getComponent(RoutedNetLayer.class);
				for (SimNetInterface simNetInterface : routedNetLayer.getSimNetworkInterfaces()) {
					//if (simNetInterface.isOffline()) {
						simNetInterface.goOnline();
					//}
				}
			} catch (ComponentNotAvailableException e) {
				e.printStackTrace();
			}

			component.updateCurrentLocation(intersections.get(i));
			component.setMovementSpeed(0.00);
		}

		if (trafficLights.size() != idComponentMatcher.size()) {
			ArrayList<String> registeredTrafficLights = new ArrayList<>(idComponentMatcher.keySet());
			for (int i = 0 ; i < registeredTrafficLights.size() ; i++) {
				String trafficLightId = registeredTrafficLights.get(i);
				trafficLights.forEach(trafficLight -> {
					if (trafficLight.getTrafficLightId().equalsIgnoreCase(trafficLightId)) {
						addFreeHost(trafficLightId);
					}
				});
			}
		}

		Event.scheduleWithDelay(timeBetweenMoveOperations,this, null, 0);
	}

	private void addFreeHost(String trafficLightId) {
		if (idComponentMatcher.containsKey(trafficLightId)) {
			SimLocationActuator simLocationActuator = idComponentMatcher.remove(trafficLightId);
			if (simLocationActuator != null) {
				try {
					TrafficLightInformationComponent trafficLightInformationComponent = simLocationActuator.getHost().getComponent(TrafficLightInformationComponent.class);
					trafficLightInformationComponent.resetTrafficLightId();
				} catch (ComponentNotAvailableException e) {
					//e.printStackTrace();
				}

				hostTrafficLightIdMatching.remove(simLocationActuator.getHost().getId());

				try {
					RoutedNetLayer routedNetLayer = simLocationActuator.getHost().getComponent(RoutedNetLayer.class);
					for (SimNetInterface simNetInterface : routedNetLayer.getSimNetworkInterfaces()) {
						if (simNetInterface.isOnline()) {
							simNetInterface.goOffline();
						}
					}
				} catch (ComponentNotAvailableException e) {
					e.printStackTrace();
				}
			}

			if (_reuseComponents) {
				freeComponents.add(simLocationActuator);
			}
		}
	}

	private SimLocationActuator requestSimActuator(String pTrafficLightId) {
		if (!idComponentMatcher.containsKey(pTrafficLightId)) {
			SimLocationActuator simLocationActuator = freeComponents.poll();

			if (simLocationActuator != null) {
				TrafficLightInformationComponent trafficLightInformationComponent;

				try {
					trafficLightInformationComponent = simLocationActuator.getHost().getComponent(TrafficLightInformationComponent.class);
				} catch (ComponentNotAvailableException e) {
					Host host = simLocationActuator.getHost();

					trafficLightInformationComponent = new DefaultTrafficLightInformationComponent(host, _controller, _extractor);
					host.registerComponent(trafficLightInformationComponent);
				}
				trafficLightInformationComponent.setTrafficLightId(pTrafficLightId);

				idComponentMatcher.put(pTrafficLightId, simLocationActuator);
				hostTrafficLightIdMatching.put(simLocationActuator.getHost().getId(), pTrafficLightId);
			} else {
				throw new RuntimeException("Unable to assign new components. Please increase node amount" + (_reuseComponents?".":" or enable the reuse of components."));
			}
		}
		return idComponentMatcher.get(pTrafficLightId);
	}
}