package com.atlassian.bitbucket.test.filters;

import com.atlassian.sal.core.features.SystemDarkFeatureInitializer;
import com.atlassian.sal.core.features.SystemDarkFeatureInitializer.SystemDarkFeatures;
import com.atlassian.bitbucket.test.annotations.DarkFeatureTest;
import org.junit.runner.Description;
import org.junit.runners.model.TestClass;

/**
 * A filter that detects {@link DarkFeatureTest annotations} and runs the test
 * only if the corresponding dark feature has been enabled / disabled through a system property
 */
public class DarkFeatureFilter extends AnnotationBasedFilter {

    private final SystemDarkFeatures systemDarkFeatures;

    public DarkFeatureFilter(TestClass testClass) {
        super(testClass);

        systemDarkFeatures = SystemDarkFeatureInitializer.getSystemStartupDarkFeatures();
    }

    @Override
    public boolean shouldRun(Description description) {
        DarkFeatureTest annotation = getAnnotation(DarkFeatureTest.class, description);

        // If the test does not have the annotation then it doesn't care.
        if (annotation == null) {
            return true;
        }

        if (systemDarkFeatures.isDisableAll()) {
            return !annotation.ifFeatureEnabled();
        }

        return annotation.ifFeatureEnabled() == systemDarkFeatures.getEnabled().contains(annotation.property());
    }

    @Override
    public String describe() {
        return String.format("Detects tests marked \"%s\" and filters them out based on the system dark feature configuration",
                DarkFeatureTest.class.getSimpleName());
    }
}
