package org.stagemonitor.web.servlet.eum;

import java.util.Collections;
import java.util.Map;

import io.opentracing.Span;

public abstract class AbstractNumberClientSpanTagProcessor<N extends Number> extends ClientSpanTagProcessor {

	private final String tagName;
	private final String requestParameterName;
	protected N lowerBound;
	protected N upperBound;
	private boolean discardSpanOnBoundViolation = false;

	public AbstractNumberClientSpanTagProcessor(String type, String tagName, String requestParameterName, N lowerBound, N upperBound) {
		super(type, Collections.singletonList(requestParameterName));
		this.tagName = tagName;
		this.requestParameterName = requestParameterName;
		this.lowerBound = lowerBound;
		this.upperBound = upperBound;
	}

	@Override
	protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) {
		final String valueOrNull = getParameterValueOrNull(requestParameterName, servletRequestParameters);
		final N parsedNumberOrNull = parsedNumberOrNull(valueOrNull);
		if (parsedNumberOrNull != null) {
			if (inBounds(parsedNumberOrNull)) {
				span.setTag(tagName, parsedNumberOrNull);
			} else if (discardSpanOnBoundViolation) {
				discardSpan(span);
			}
		}
	}

	protected abstract boolean inBounds(N value);

	public AbstractNumberClientSpanTagProcessor<N> lowerBound(N lowerBound) {
		this.lowerBound = lowerBound;
		return this;
	}

	public AbstractNumberClientSpanTagProcessor<N> upperBound(N upperBound) {
		this.upperBound = upperBound;
		return this;
	}

	public AbstractNumberClientSpanTagProcessor<N> discardSpanOnBoundViolation(boolean discardSpanOnBoundViolation) {
		this.discardSpanOnBoundViolation = discardSpanOnBoundViolation;
		return this;
	}

	protected N parsedNumberOrNull(String valueOrNull) {
		try {
			return parse(valueOrNull);
		} catch (NumberFormatException e) {
			return null;
		}
	}

	protected abstract N parse(String valueOrNull);

}

@@ -36,16 +36,74 @@
 t.eum;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A
 import j
@@ -124,16 +124,16 @@
 ctions;%0A
-
 import j
@@ -287,16 +287,123 @@
 ssor %7B%0A%0A
+%09private static final Logger logger = LoggerFactory.getLogger(AbstractNumberClientSpanTagProcessor.class);%0A
 %09private
@@ -1349,24 +1349,178 @@
 iolation) %7B%0A
+%09%09%09%09logger.info(%22discarding %7B%7D for illegal value '%7B%7D': not in bounds (%7B%7D %3C= %7B%7D %3C= %7B%7D)%22,%0A%09%09%09%09%09%09tagName, valueOrNull, lowerBound, valueOrNull, upperBound);%0A
 %09%09%09%09discardS
@@ -2135,16 +2135,16 @@
 rNull);%0A
-
 %09%09%7D catc
@@ -2173,16 +2173,118 @@
 on e) %7B%0A
+%09%09%09logger.info(%22discarding %7B%7D for illegal value '%7B%7D': not a parseable number%22, tagName, valueOrNull);%0A
 %09%09%09retur

improve end user monitoring logging on bound violation