package com.atlassian.bitbucket.mesh.metrics;

import com.google.common.collect.ImmutableSet;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import javax.annotation.Nonnull;
import java.util.Set;

/**
 * A Spring condition for configuration that should only be activated when the one or more metrics exporters are
 * enabled.
 */
public class MetricsEnabledCondition implements ConfigurationCondition {

    private static final Set<String> REGISTRIES = ImmutableSet.of(
            "datadog",
            "dynatrace",
            "influx",
            "jmx",
            "new-relic",
            "signalfx",
            "statsd"
    );

    @Nonnull
    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }

    @Override
    public boolean matches(ConditionContext context, @Nonnull AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        return REGISTRIES.stream()
                .map(name -> "management.metrics.export." + name + ".enabled")
                .anyMatch(property -> environment.getProperty(property, Boolean.class, Boolean.FALSE));
    }
}
