package com.atlassian.bitbucket.web.conditions;

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

import java.util.Map;

/**
 * Checks for a "repository" in the context and displays if that repository has a specified
 * {@link Repository#getScmId() SCM}. If the context does not contain a "repository" the
 * associated component will <i>not</i> be displayed.
 * <p>
 * Usage:
 * <pre><code>
 * &lt;condition class="com.atlassian.bitbucket.web.conditions.IsScmCondition"&gt;
 *     &lt;param name="key"&gt;repository&lt;/param&gt;
 *     &lt;param name="scm"&gt;git&lt;/param&gt;
 * &lt;/condition&gt;
 * </code></pre>
 * <p>
 * The "key" param is <i>optional</i>, and defaults to "repository" if not set. That's appropriate for most
 * contexts. An example of a place where the "key" might be set is when using this condition for a fragment
 * on "bitbucket.internal.page.repository.fork", where the context contains "upstream" and "fork" rather than "repository".
 */
public class IsScmCondition implements Condition {

    private static final String SCM = "scm";

    private String key;
    private String scm;

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
        key = StringUtils.defaultIfBlank(params.get("key"), "repository");

        scm = params.get(SCM);
        if (StringUtils.isBlank(scm)) {
            throw new PluginParseException(getClass().getSimpleName() + ": The [" + SCM + "] param is required");
        }
    }

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        Repository repository = (Repository) context.get(key);

        return repository != null && scm.equals(repository.getScmId());
    }
}
