/*
 * 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.analyzer.metric.filter;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric.MetricValue;

/**
 * calculates the delivery ratio, which is the percent of actual transferred
 * messages. (1 - overhead). Uses the duplicate and message count metrics and
 * merge them. Used metrics are in DELIVERY_RATIO_LIST and duplicate metric must
 * end with "Dup".
 * 
 * @author Simon Luser
 * @version 1.0, 08.03.2017
 */
public class MergeDeliveryRatioFilter
		extends AbstractFilter<MetricValue<Double>> {

	@Override
	public void onStop() {
		// nothing to do
	}

	@Override
	public String getName() {
		return "DeliveryRatio";
	}

	@Override
	protected void onInitialize(List<Metric<?>> incomingMetrics) {
		// get the pairing metrics
		Set<Metric<?>> duplicateMetrics = incomingMetrics.stream().filter(
				m -> m.getName().endsWith("Dup") && !m.isOverallMetric())
				.collect(Collectors.toSet());
		Set<Metric<?>> nonDuplicateMetrics = incomingMetrics.stream().filter(
				m -> !m.getName().endsWith("Dup") && !m.isOverallMetric())
				.collect(Collectors.toSet());

		// generate the matches and create derived metric
		for (Metric<?> met : nonDuplicateMetrics) {
			List<Metric<?>> matches = duplicateMetrics.stream()
					.filter(m -> met.getName()
							.startsWith(m.getName().substring(0,
									m.getName().lastIndexOf("Dup"))))
					.collect(Collectors.toList());
			if (matches.size() > 1)
				Monitor.log(MergeDeliveryRatioFilter.class, Level.ERROR,
						"Config Error!");
			else if (matches.size() == 1) {
				matches.add(met);
				createDerivedMetric(matches, false, met.getUnit(),
						"Delivery Ratio", false);
			}
		}
	}

	@Override
	protected String getNameForDerivedMetric(List<Metric<?>> inputs) {
		String str = getName();

		if (inputs.size() >= 1) {
			str += "_";

			String firstName = inputs.get(0).getName();
			if (firstName.contains("Dup"))
				str += firstName.substring(0, firstName.lastIndexOf("Dup"));
			else
				str += firstName;
		}

		return str;
	}

	@Override
	protected MetricValue<Double> getDerivedMetricValueFor(
			Metric<?> derivedMetric, List<Metric<?>> inputs, Host host) {
		// separate the values
		if (inputs.size() == 2) {
			try {
				MetricValue<?> duplicateVal = inputs.stream()
						.filter(m -> m.getName().endsWith("Dup"))
						.collect(Collectors.toList()).get(0)
						.getPerHostMetric(host.getId());
				MetricValue<?> receiveVal = inputs.stream()
						.filter(m -> !m.getName().endsWith("Dup"))
						.collect(Collectors.toList()).get(0)
						.getPerHostMetric(host.getId());
				if (duplicateVal == null || receiveVal == null) {
					return null;
				}

				return new DeliveryRatioMetricValue(duplicateVal, receiveVal);
			} catch (IndexOutOfBoundsException e) {
				return null;
			}
		} else
			return null;
	}

	/**
	 * calculates the delivery ratio.
	 * 
	 * @author Simon Luser
	 * @version 1.0, 08.03.2017
	 */
	private class DeliveryRatioMetricValue implements MetricValue<Double> {

		private MetricValue<?> duplicateVal, receiveVal;

		private boolean valid;

		public DeliveryRatioMetricValue(MetricValue<?> duplicateVal,
				MetricValue<?> receiveVal) {
			this.duplicateVal = duplicateVal;
			this.receiveVal = receiveVal;
		}

		@Override
		public Double getValue() {
			Object oDup = duplicateVal.getValue();
			Object oRec = receiveVal.getValue();

			double nDup;
			if (oDup instanceof Number) {
				nDup = ((Number) oDup).doubleValue();
			} else {
				throw new AssertionError();
			}

			double nRec;
			if (oRec instanceof Number) {
				nRec = ((Number) oRec).doubleValue();
			} else {
				throw new AssertionError();
			}

			this.valid = duplicateVal.isValid() && receiveVal.isValid()
					&& nRec > 0;

			return 1 - nDup / nRec;
		}

		@Override
		public boolean isValid() {
			return valid;
		}
	}
}
