/*
 * 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.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
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.SimpleQoIBasedImpactFunction;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.RoadProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralJamProperty;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.environment.data.properties.vectoral.VectoralProperty;
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.AvailableInformationAttributes;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.PointInformation;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.information.RoadInformation;

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

	private static final double ACCURACY_FACTOR = 100000;

	private final Map<CacheDecisionStrategyParameters, String> _params;

	private long ttl = 300 * Time.SECOND / SCALING;
	private double accuracy = 1;

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

	private Object _lastDecision = false;

	private int _maxCacheSize = Integer.MAX_VALUE;

	@TransferState(value = { "Params" })
	public TTLbasedCacheDecisionStrategy(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());
			}

		});

		Object value = pSimilarPointInformation.get(0).getValue();
		boolean differentValue = false;
		for (T t : pSimilarPointInformation) {
			if (!value.equals(t.getValue())) {
				differentValue = true;
			}
		}

		SimpleQoIBasedImpactFunction<T> impactFunction = new SimpleQoIBasedImpactFunction<>(pSimilarPointInformation, accuracy, _maxCacheSize);

		Map<Object, Double> weight = new HashMap<>();

		for (T t : pSimilarPointInformation) {
			double impact = impactFunction.calculateImpact(t);

			double sumImpact = 0;

			Object currentValue = t.getValue();

			if (currentValue instanceof VectoralJamProperty) {
				currentValue = ((VectoralJamProperty) currentValue).getMostProbableValue();
			}

			if (weight.containsKey(currentValue)) {
				sumImpact = weight.get(currentValue);
			}
			sumImpact += impact;

			weight.put(currentValue, sumImpact);
		}

		double maxWeight = -1;
		Object maxValue = null;

		for (Object key : weight.keySet()) {
			if (weight.get(key) > maxWeight) {
				maxWeight = weight.get(key);
				maxValue = key;
			}
		}

		long maxTimestamp = -1;
		T maxFitting = null;
		for (T t : pSimilarPointInformation) {
			long timestamp = t.getDetectionDate();

			Object currentValue = t.getValue();
			if (currentValue instanceof VectoralProperty) {
				currentValue = ((VectoralProperty)currentValue).getMostProbableValue();
			}

			if (currentValue.equals(maxValue) && timestamp > maxTimestamp) {
				maxTimestamp = timestamp;
				maxFitting = t;
			}
		}

		if (maxFitting.getValue() instanceof VectoralProperty) {
			VectoralProperty vectoralProperty = ((VectoralProperty)maxFitting.getValue()).clone();
			double[] valueProbabilities = vectoralProperty.getValueProbabilities();
			Arrays.fill(valueProbabilities, 0);

			double sum = 0;
			for (Object key : weight.keySet()) {
				valueProbabilities[vectoralProperty.getIndexForValue(key)] = weight.get(key);
				sum += weight.get(key);
			}

			for (int i = 0; i < valueProbabilities.length; i++) {
				valueProbabilities[i] /= sum;
			}

			RoadInformation roadInformation = new RoadInformation(vectoralProperty);
			roadInformation.copyAttributes((RoadInformation)maxFitting);
			maxFitting = (T) roadInformation;
		}

		_lastDecision = maxFitting.getValue();

		addAggregationInformation(pSimilarPointInformation, maxFitting);

		return maxFitting;
	}

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

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

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