package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.ScmFeature;
import com.atlassian.bitbucket.scm.ScmService;
import org.apache.commons.lang3.StringUtils;

import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class IsScmFeatureSupportedCondition implements Condition {

    private final ScmService scmService;

    private Set<ScmFeature> features;

    public IsScmFeatureSupportedCondition(ScmService scmService) {
        this.scmService = scmService;

        features = EnumSet.noneOf(ScmFeature.class);
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
        parseFeature(params);
        parseFeatures(params);

        if (features.isEmpty()) {
            throw new PluginParseException("At least one ScmFeature must be specified. " +
                    "Use the \"feature\" or \"features\" parameters to provide ScmFeatures.");
        }
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        Repository repository = (Repository) context.get("repository");
        if (repository == null) {
            return false;
        }

        for (ScmFeature feature : features) {
            if (!scmService.isSupported(repository, feature)) {
                return false;
            }
        }

        return true;
    }

    private void addFeature(String value) throws PluginParseException {
        try {
            features.add(ScmFeature.parse(value));
        } catch (IllegalArgumentException e) {
            throw new PluginParseException("\"" + value + "\" is not a valid ScmFeature.", e);
        }
    }

    private void parseFeature(Map<String, String> params) throws PluginParseException {
        String feature = params.get("feature");
        if (StringUtils.isNotBlank(feature)) {
            addFeature(feature);
        }
    }

    private void parseFeatures(Map<String, String> params) throws PluginParseException {
        String features = params.get("features");
        if (StringUtils.isNotBlank(features)) {
            for (String feature : features.split(",")) {
                addFeature(feature);
            }
        }
    }
}
