package me.bvn13.logging;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class IgnoringActuatorLoggingFilter extends Filter<ILoggingEvent> {
    private static final Pattern ACTUATOR =
            Pattern.compile("GET \"/(health|prometheus)\", parameters=\\{}");
    private static final Pattern COMPLETED =
            Pattern.compile("Completed 200 OK");

    private final Set<String> activeThreads = new HashSet<>();

    @Override
    public FilterReply decide(ILoggingEvent loggingEvent) {
        if (isHealthOrPrometheus(loggingEvent.getMessage())) {
            activeThreads.add(loggingEvent.getThreadName());
            return FilterReply.DENY;
        } else if (isCompleted200Ok(loggingEvent.getMessage()) && activeThreads.remove(loggingEvent.getThreadName())) {
            return FilterReply.DENY;
        } else {
            return FilterReply.ACCEPT;
        }
    }

    private boolean isHealthOrPrometheus(String message) {
        return ACTUATOR.matcher(message).matches();
    }

    private boolean isCompleted200Ok(String message) {
        return COMPLETED.matcher(message).matches();
    }
}
