/*
 * 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.vehicular.caching.decision;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.relevance.vehicular.impl.VectoralQoIBasedImpactFunction;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.TemporalDependencyMatrix;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.aggregation.AggregationInformation;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.RoadProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
import de.tudarmstadt.maki.simonstrator.api.component.transition.MechanismState;
import de.tudarmstadt.maki.simonstrator.api.component.transition.TransferState;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.AbstractCacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategy;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheDecisionStrategyParameters;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.caching.decision.CacheSizeAwareCacheDecisionStrategy;
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.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;

public class TTLbasedVectoralCacheDecisionStrategy extends AbstractCacheDecisionStrategy implements CacheSizeAwareCacheDecisionStrategy {
	private static final long SCALING = Time.SECOND;

	private final Map<CacheDecisionStrategyParameters, String> _params;

	private double accuracy = 1;

	private double costWrongKeep = 1;
	private double costWrongChange = 1;

	private int cacheSize = Integer.MAX_VALUE;

	private Object _lastDecision = null;

	@TransferState(value = { "Params" })
	public TTLbasedVectoralCacheDecisionStrategy(Map<CacheDecisionStrategyParameters, String> pParams) {
		_params = pParams;

		for (Entry<CacheDecisionStrategyParameters, String> param : pParams.entrySet()) {
			switch (param.getKey()) {
			case ACCURACY:
				accuracy = Double.valueOf(param.getValue());
				break;
			case COST_RATIO:
				double ratio = Double.valueOf(param.getValue());
				costWrongChange = 2 / (ratio + 1);
				costWrongKeep = 2 - costWrongChange;
				break;
			default:
				break;
			}
		}
	}

	public double getCostWrongChange() {
		return costWrongChange;
	}

	public double getCostWrongKeep() {
		return costWrongKeep;
	}

	@Override
	public <T extends PointInformation> T decideOnCorrectInformation(
			List<T> pSimilarPointInformation) {
		if (pSimilarPointInformation.size() == 1) {
			T decision = pSimilarPointInformation.get(0);
			addAggregationInformation(pSimilarPointInformation, decision);

			_lastDecision = decision.getValue();
			return decision;
		} else if (pSimilarPointInformation.size() == 0) {
			return null;
		}

		Collections.sort(pSimilarPointInformation, new Comparator<T>() {

			@Override
			public int compare(T pArg0, T pArg1) {
				return Long.compare(pArg0.getDetectionDate(), pArg1.getDetectionDate());
			}

		});

		long minTimestamp = Long.MAX_VALUE;
		long maxTimestamp = 0;
		Object value = pSimilarPointInformation.get(0).getValue();
		if (value instanceof VectoralProperty) {
			value = ((VectoralProperty) value).getMostProbableIndex();
		}
		boolean differentValue = true;

		if (differentValue) {
			List<Integer> possibleValues = new ArrayList<>();

			for (T t : pSimilarPointInformation) {
				if (!t.hasAttribute(AvailableInformationAttributes.TTL)) {
					throw new AssertionError("Unable to perform TTL-based majority voting witout TTL");
				}
				long timestamp = t.getDetectionDate();

				if (timestamp < minTimestamp) {
					minTimestamp = timestamp;
				}
				if (timestamp > maxTimestamp) {
					maxTimestamp = timestamp;
				}

				Object currentValue = t.getValue();
				if (currentValue instanceof VectoralProperty) {
					VectoralProperty currentProperty = (VectoralProperty) currentValue;
					currentValue = currentProperty.getMostProbableIndex();

					if (!value.equals(currentValue)) {
						differentValue = true;
					}

					for (int i = 0; i < currentProperty.getValueProbabilities().length; i++) {
						if (!possibleValues.contains(i)) {
							possibleValues.add(i);
						}
					}
				}

				if (t instanceof AggregatedInformation) {
					AggregationInformation aggregationInformation = ((AggregatedInformation)t).getAggregationInformation();
					if (aggregationInformation != null && aggregationInformation.getMinTimestamp() < minTimestamp) {
						minTimestamp = aggregationInformation.getMinTimestamp();
					}
				}
			}

			VectoralProperty currentProperty = null;

			VectoralQoIBasedImpactFunction<T> impactFunction = new VectoralQoIBasedImpactFunction<>(pSimilarPointInformation, accuracy, cacheSize, _lastDecision);
			for (T t : pSimilarPointInformation) {
				RoadInformation roadInformation = ((RoadInformation) t);
				VectoralProperty property = (VectoralProperty) roadInformation.getValue();

				double impact = impactFunction.calculateImpact(t);

				TemporalDependencyMatrix dependencyMatrix = property.getDependencyMatrix();
				dependencyMatrix = modifyDependencyMatrix(dependencyMatrix.age((maxTimestamp - property.getDetectionDate()) / SCALING), impact);

				VectoralProperty agedProperty = property.age(1, dependencyMatrix);
				if (currentProperty != null) {
					currentProperty = currentProperty.combine(agedProperty);
				} else {
					currentProperty = agedProperty;
				}
			}

			if (Double.isNaN(currentProperty.getValueProbabilities()[0])) {
				return pSimilarPointInformation.get(pSimilarPointInformation.size() - 1);
			}

			RoadInformation roadInformation = new RoadInformation(currentProperty);

			copyAttributes((RoadInformation) pSimilarPointInformation.get(pSimilarPointInformation.size() - 1), roadInformation);
			addAggregationInformation(pSimilarPointInformation, roadInformation);

			_lastDecision = roadInformation.getValue();

			return (T) roadInformation;
		} else {
			RoadProperty currentProperty = (RoadProperty) pSimilarPointInformation.get(pSimilarPointInformation.size() - 1).getValue();

			RoadInformation roadInformation = new RoadInformation(currentProperty );

			copyAttributes((RoadInformation) pSimilarPointInformation.get(pSimilarPointInformation.size() - 1), roadInformation);
			addAggregationInformation(pSimilarPointInformation, roadInformation);

			_lastDecision = roadInformation.getValue();

			return (T) roadInformation;
		}
	}

	/**
	 * @param pT
	 * @param pRoadInformation
	 */
	private void copyAttributes(RoadInformation pSrc, RoadInformation pDest) {
		for (AvailableInformationAttributes attribute : pSrc.getAvailableAttributes()) {
			pDest.setAttribute(attribute, pSrc.getAttribute(attribute));
		}
	}

	private TemporalDependencyMatrix modifyDependencyMatrix(
			TemporalDependencyMatrix pDependencyMatrix, double pImpact) {
		TemporalDependencyMatrix result = pDependencyMatrix.clone();

		double[][] dependencies = result.getDependencies();
		for (int i = 0; i < dependencies.length; i++) {
			double finalPercentages = 1.0 / dependencies[i].length;

			for (int j = 0; j < dependencies[i].length; j++) {
				dependencies[i][j] = finalPercentages + (pDependencyMatrix.getDependencies()[i][j] - finalPercentages) * pImpact;
			}
		}

		return result;
	}

	public Map<CacheDecisionStrategyParameters, String> getParams() {
		return _params;
	}

	@Override
	public void setCacheSize(int pCacheSize) {
		cacheSize = pCacheSize;
	}

	@Override
	public TTLbasedVectoralCacheDecisionStrategy clone() {
		return new TTLbasedVectoralCacheDecisionStrategy(_params);
	}

}
