/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of Simonstrator.KOM.
 *
 * Simonstrator.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.vehicular.caching;

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

import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.common.graph.INodeID;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.network.NetInterface;
import de.tudarmstadt.maki.simonstrator.api.component.network.NetworkComponent.NetInterfaceName;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransitionEngine;
import de.tudarmstadt.maki.simonstrator.api.component.transport.ConnectivityListener;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.VehicleInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CacheStateListener;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.CachingComponent;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheSizeAwareCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.invalidation.CacheInvalidationStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.replacement.CacheReplacementStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AggregatedInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.JamInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetwork;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkRoute;

public class DefaultCachingComponent implements CachingComponent, ConnectivityListener {

	private Map<Class<? extends Object>, List<PointInformation>> _cache = new HashMap<>();

	private Map<Integer, Integer> _lastColorValues = new HashMap<>();

	private Host _host;

	private CacheInvalidationStrategy _invalidationStrategy;

	private CacheReplacementStrategy _replacementStrategy;

	private CacheDecisionStrategy _defaultDecisionStrategy;
	private Map<Class<? extends Object>, CacheDecisionStrategy> _decisionStrategies = new HashMap<>();

	private int _minObservations = 0;

	private int _maxCacheSize = Integer.MAX_VALUE;

	private double[] informationRatios = new double[] {1, 0.75, 0.5, 0.25, 0};

	private List<CacheStateListener> _cacheStateListeners = new ArrayList<>();

	public DefaultCachingComponent(Host pHost,
			CacheInvalidationStrategy pInvalidationStrategy,
			CacheReplacementStrategy pReplacementStrategy,
			CacheDecisionStrategy pDecisionStrategy) {
		_host = pHost;

		if (_host != null) {
			NetInterface cellular = _host.getNetworkComponent().getByName(NetInterfaceName.MOBILE);
			cellular.addConnectivityListener(this);
		}

		_invalidationStrategy = pInvalidationStrategy;
		_replacementStrategy = pReplacementStrategy;
		_defaultDecisionStrategy = pDecisionStrategy;
	}

	private TransitionEngine getTransitionEngine() throws AssertionError {
		try {
			return getHost().getComponent(TransitionEngine.class);
		} catch (ComponentNotAvailableException e) {
			throw new AssertionError("Unable to get transition engine!");
		}
	}

	@Override
	public void registerCacheStateListener(CacheStateListener pListener) {
		_cacheStateListeners.add(pListener);
	}

	@Override
	public <T extends PointInformation> List<T> getDecidedCacheEntries(
			Class<T> pCacheEntryClass) {
		CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(pCacheEntryClass);
		Set<RoadNetworkEdge> allEverActiveEdges = RoadNetwork.CURRENT_ROAD_NETWORK.getAllEverActiveEdges();

		List<T> cacheEntries = getCacheEntries(pCacheEntryClass);

		if (cacheEntries == null) {
			return null;
		}

		Map<Object, Map<Class<? extends Object>, List<PointInformation>>> similarCacheEntries = new HashMap<>();

		for (T t : cacheEntries) {
			Object position = getEdgeOrPosition(t);

			if (!(position instanceof RoadNetworkEdge) || allEverActiveEdges.contains((position))) {
				if (!similarCacheEntries.containsKey(position)) {
					similarCacheEntries.put(position, new HashMap<>());
				}
				if (!similarCacheEntries.get(position).containsKey(t.getValue().getClass())) {
					similarCacheEntries.get(position).put(t.getValue().getClass(), new ArrayList<PointInformation>());
				}
				similarCacheEntries.get(position).get(t.getValue().getClass()).add(t);
			}

		}

		List<T> decidedInformation = new ArrayList<>();
		for (Map<Class<? extends Object>, List<PointInformation>> similarEdges : similarCacheEntries
				.values()) {
			for (List<PointInformation> similarInformation : similarEdges.values()) {
				if (similarInformation.size() >= _minObservations) {
					PointInformation correctInformation = decisionStrategy
							.decideOnCorrectInformation(similarInformation);

					decidedInformation.add((T) correctInformation);
				}
			}
		}

		return decidedInformation;
	}

	@Override
	public <T extends PointInformation> List<T> getDecidedCacheEntries(
			Class<T> pCacheEntryClass, RoadNetworkEdge pEdge) {
		return getDecidedCacheEntries(pCacheEntryClass, null, pEdge);
	}

	@Override
	public <T extends PointInformation> List<T> getDecidedCacheEntries(
			Class<T> pCacheEntryClass, Class<?> pCacheValueClass, RoadNetworkEdge pEdge) {
	    return getDecidedCacheEntries(pCacheEntryClass, pCacheValueClass, pEdge, null);
	}

	@Override
	public <T extends PointInformation> List<T> getDecidedCacheEntries(Class<T> pCacheEntryClass, Class<?> pCacheValueClass,
            RoadNetworkEdge pEdge, INodeID pWithoutID) {
	    CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(pCacheEntryClass);
	    Set<RoadNetworkEdge> allEverActiveEdges = RoadNetwork.CURRENT_ROAD_NETWORK.getAllEverActiveEdges();

	    if (!allEverActiveEdges.contains(pEdge)) {
	        return null;
	    }

	    List<T> cacheEntries = getCacheEntries(pCacheEntryClass);

	    if (cacheEntries == null) {
	        return null;
	    }

	    Map<Class<? extends Object>, List<PointInformation>> similarCacheEntries = new HashMap<>();

	    for (T t : cacheEntries) {
	        if (pWithoutID == null || !t.getAttribute(AvailableInformationAttributes.OWNER).equals(pWithoutID)) {
	            Object position = getEdgeOrPosition(t);

	            if (position.equals(pEdge) && (pCacheValueClass == null || t.getValue().getClass().equals(pCacheValueClass))) {
	                if (!similarCacheEntries.containsKey(t.getValue().getClass())) {
	                    similarCacheEntries.put(t.getValue().getClass(), new ArrayList<PointInformation>());
	                }
	                similarCacheEntries.get(t.getValue().getClass()).add(t);
	            }
	        }
	    }

	    List<T> decidedInformation = new ArrayList<>();

	    for (List<PointInformation> similarInformation : similarCacheEntries.values()) {
	        if (similarInformation.size() >= _minObservations) {
	            PointInformation correctInformation = decisionStrategy
	                    .decideOnCorrectInformation(similarInformation);

	            decidedInformation.add((T) correctInformation);
	        }
	    }

	    return decidedInformation;
	}

	private <T extends PointInformation> CacheDecisionStrategy getCacheDecisionStrategy(Class<T> pCacheEntryClass)
			throws AssertionError {
		if (!_decisionStrategies.containsKey(pCacheEntryClass)) {
			CacheDecisionStrategy clone = _defaultDecisionStrategy.clone();

			TransitionEngine tEngine = getTransitionEngine();
			clone = tEngine.createMechanismProxy(CacheDecisionStrategy.class, clone, DECISION_STRATEGY + pCacheEntryClass.getSimpleName());

			_decisionStrategies.put(pCacheEntryClass, clone);
		}

		CacheDecisionStrategy decisionStrategy = _decisionStrategies.get(pCacheEntryClass);
		return decisionStrategy;
	}

	public void setMinObservations(int pMinObservations) {
		this._minObservations = pMinObservations;
	}

	@Override
	public <T extends PointInformation> List<T> getCacheEntries(
			Class<T> pCacheEntryClass) {
		if (_cache.containsKey(pCacheEntryClass)) {
			List<? extends PointInformation> cacheEntries = _cache
					.get(pCacheEntryClass);
			List<T> results = new ArrayList<>();

			for (int i = 0; i < cacheEntries.size(); i++) {
				PointInformation object = cacheEntries.get(i);
				if (_invalidationStrategy.checkInformation(object)) {
					cacheEntries.remove(i--);
					continue;
				}
				results.add((T) object);
			}

			return results;
		}
		return null;
	}

	@Override
	public <T extends PointInformation> boolean containsEntry(T pCacheEntry) {
		if (_cache.containsKey(pCacheEntry.getClass())) {
			List<? extends Object> cacheEntries = _cache.get(pCacheEntry.getClass());
			return cacheEntries.contains(pCacheEntry);
		}
		return false;
	}

	@Override
	public <T extends PointInformation> void storeCacheEntry(T pCacheEntry) {
		if (!_cache.containsKey(pCacheEntry.getClass())) {
			_cache.put(pCacheEntry.getClass(), new ArrayList<>());
		}

		List<PointInformation> entries = _cache.get(pCacheEntry.getClass());

		if (pCacheEntry instanceof AggregatedInformation && ((AggregatedInformation) pCacheEntry).isAggregated()) {
			List<PointInformation> toBeRemoved = new ArrayList<>();
			for (PointInformation pointInformation : entries) {
				if (_replacementStrategy.replaceInformation(pointInformation, pCacheEntry)) {
					toBeRemoved.add(pointInformation);
				}
			}
			for (PointInformation pointInformation : toBeRemoved) {
				entries.remove(pointInformation);
			}
		}

		shrinkCache(_maxCacheSize);

		entries.add(pCacheEntry);

		for (CacheStateListener cacheStateListener : _cacheStateListeners) {
			cacheStateListener.entryStored(pCacheEntry);
		}
	}

	private void shrinkCache(int maxSize) {
		while (getTotalCacheSize() > maxSize) {
			int maxSizeValue = 0;
			List<PointInformation> removedValues = null;
			List<PointInformation> removedList = null;

			for (List<PointInformation> informationList : _cache.values()) {
				Map<Object, List<PointInformation>> perPosition = new HashMap<>();

				for (PointInformation pointInformation : informationList) {
					Object position = getEdgeOrPosition(pointInformation);
					if (!perPosition.containsKey(position)) {
						perPosition.put(position, new ArrayList<>());
					}

					perPosition.get(position).add(pointInformation);
				}

				for (Entry<Object, List<PointInformation>> entry : perPosition.entrySet()) {
					if (!((RoadNetworkEdge) entry.getKey()).isActive()) {
						removedValues = entry.getValue();
						removedList = informationList;

						break;
					}

					if (maxSizeValue < entry.getValue().size()) {
						maxSizeValue = entry.getValue().size();
						removedValues = entry.getValue();
						removedList = informationList;
					}
				}
			}

			removedList.removeAll(removedValues);

			CacheDecisionStrategy decisionStrategy = getCacheDecisionStrategy(removedValues.get(0).getClass());

			PointInformation correctInformation = decisionStrategy
					.decideOnCorrectInformation(removedValues);

			for (CacheStateListener cacheStateListener : _cacheStateListeners) {
				cacheStateListener.entriesRemoved(removedValues, correctInformation);
			}
		}
	}

	private int getTotalCacheSize() {
		int sum = 0;
		for (List<PointInformation> informationList : _cache.values()) {
			sum += informationList.size();
		}
		return sum;
	}

	@Override
	public void initialize() {
		_cache.clear();
	}

	@Override
	public void shutdown() {
	}

	@Override
	public Host getHost() {
		return _host;
	}

	@Override
	public void wentOnline(Host pHost, NetInterface pNetInterface) {
		_cache.clear();
	}

	@Override
	public void wentOffline(Host pHost, NetInterface pNetInterface) {

	}

	@Override
	public void performDecisionTransition(Class<? extends Object> pInformationClass, Class<? extends CacheDecisionStrategy> pCacheDecisionStrategy) {
		getTransitionEngine().executeAtomicTransition(DECISION_STRATEGY + pInformationClass.getSimpleName(), pCacheDecisionStrategy);
	}

	@Override
	public void setMaxSize(int pMaxCacheSize) {
		_maxCacheSize = pMaxCacheSize;

		shrinkCache(_maxCacheSize);
	}

	@Override
	public void adjustCacheSizePerEntry(Class<? extends Object> pInformationClass, int pMaxCacheSizePerEntry) {
		getTransitionEngine().alterLocalState(DECISION_STRATEGY + pInformationClass.getSimpleName(), CacheSizeAwareCacheDecisionStrategy.class, "CacheSize", pMaxCacheSizePerEntry);
	}

	@Override
	public void clear() {
		_cache.clear();
	}

	@Override
	public <T extends PointInformation> void partialClear(Class<T> pCacheEntryClass, Class<?> pCacheValueClass, RoadNetworkEdge pEdge) {
		List<PointInformation> cacheEntries = _cache.get(pCacheEntryClass);

		if (cacheEntries == null) {
			return;
		}

		List<PointInformation> toBeRemoved = new ArrayList<>();
		for (PointInformation entry : cacheEntries) {
			if ((pEdge == null || getEdgeOrPosition(entry).equals(pEdge))
					&& (pCacheEntryClass == null || entry.getValue().getClass().equals(pCacheValueClass))) {
				toBeRemoved.add(entry);
			}
		}

		cacheEntries.removeAll(toBeRemoved);
	}

	public Object getEdgeOrPosition(PointInformation information) {
		if (information.hasAttribute(AvailableInformationAttributes.EDGE)) {
			return information
					.getAttribute(AvailableInformationAttributes.EDGE);
		} else if (information instanceof RoadInformation) {
		    return ((RoadInformation) information).getEdge();
		} else {
			return information.getLocation();
		}
	}

	@Override
	public String getNodeDescription() {
	    if (getHost().getId().value() > 47) {
	        return "    " + getHost().getId();
	    }
	    return "";
	}

	@Override
	public int getNodeColorDimensions() {
		return 2;
	}

	@Override
	public String[] getNodeColorDimensionDescriptions() {
		return new String[] {"Route Information", "Number of jam information"};
	}

	@Override
	public String[] getNodeColorDescriptions(int pDimension) {
		if (pDimension == 0) {
			String[] labels = new String[informationRatios.length];
			for (int i = 0; i < informationRatios.length; i++) {
				labels[i] = informationRatios[i] * 100 + "%";
			}
			return labels;
		} else if (pDimension == 1) {
			String[] numbers = new String[10];
			for (int i = 0; i < numbers.length; i++) {
				numbers[i] = String.valueOf(i);
			}
			return numbers;
		}
		return new String[0];
	}

	@Override
	public int getNodeColor(int pDimension) {
		if (pDimension == 0) {
			List<JamInformation> decidedCacheEntries = getDecidedCacheEntries(JamInformation.class);
			try {
				VehicleInformationComponent vehicleInformationComponent = getHost().getComponent(VehicleInformationComponent.class);
				if (vehicleInformationComponent.isValid()) {
					RoadNetworkRoute currentRoute = vehicleInformationComponent.getCurrentRoute();
					if (currentRoute != null) {
						int count = 0;
						int active = 0;
						for (RoadNetworkEdge edge : currentRoute.getRoute()) {
							if (edge.isActive()) {
								if (decidedCacheEntries != null) {
									for (JamInformation jamInformation : decidedCacheEntries) {
										if (jamInformation.getEdge().equals(edge) && jamInformation.getValue()) {
											count++;
											break;
										}
									}
								}
								active++;
							}
						}
						if (active != 0) {
							double ratio = count / ((double) active);
							for (int i = 0; i < informationRatios.length; i++) {
								if (informationRatios[i] <= ratio) {
									_lastColorValues.put(pDimension, i);
									break;
								}
							}
						} else {
							_lastColorValues.put(pDimension, 0);
						}
					}
				}
			} catch (ComponentNotAvailableException e) {
			}
			if (_lastColorValues.containsKey(pDimension)) {
				return _lastColorValues.get(pDimension);
			}
			return 0;
		}
		if (pDimension == 1) {
			List<JamInformation> decidedCacheEntries = getDecidedCacheEntries(JamInformation.class);
			if (decidedCacheEntries != null) {
				_lastColorValues.put(pDimension, decidedCacheEntries.size());
			}
			if (_lastColorValues.containsKey(pDimension)) {
				return Math.min(9, _lastColorValues.get(pDimension));
			}
			return 0;
		}
		return 0;
	}

	@Override
	public boolean isActive() {
		return getHost().getNetworkComponent().getByName(NetInterfaceName.MOBILE).isUp()
				|| getHost().getNetworkComponent().getByName(NetInterfaceName.WIFI).isUp();
	}
}
