package com.atlassian.bitbucket.web.conditions;

import com.atlassian.bitbucket.server.StandardFeature;
import com.atlassian.bitbucket.server.FeatureManager;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Checks whether a configured {@link StandardFeature} is {@link FeatureManager#isEnabled(StandardFeature) is enabled}.
 */
public class IsFeatureEnabledCondition implements Condition {

    static final String KEY = "key";

    private final FeatureManager featureManager;

    private StandardFeature feature;

    public IsFeatureEnabledCondition(FeatureManager featureManager) {
        this.featureManager = featureManager;
    }

    protected IsFeatureEnabledCondition(FeatureManager featureManager, StandardFeature feature) {
        this.featureManager = featureManager;
        this.feature = checkNotNull(feature, "feature");
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
        if (feature == null) {
            String featureKeyAsString = params.get(KEY);
            if (StringUtils.isBlank(featureKeyAsString)) {
                throw new PluginParseException(getClass().getSimpleName() + " requires the parameter " + KEY);
            }
            feature = StandardFeature.fromKey(featureKeyAsString);
        }
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        return featureManager.isEnabled(feature);
    }
}
