package com.atlassian.stash.internal.web.soy.functions;

import com.atlassian.soy.renderer.SoyServerFunction;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.RepositoryService;
import com.atlassian.bitbucket.scm.ScmFeature;
import com.atlassian.bitbucket.scm.ScmService;
import com.google.common.collect.ImmutableSet;

import java.util.Set;

/**
 * @since 3.4
 */
public class IsScmFeatureSupportedFunction implements SoyServerFunction<Boolean> {

    private static final Set<Integer> VALID_SIZES = ImmutableSet.of(2, 3);

    private final RepositoryService repositoryService;
    private final ScmService scmService;

    public IsScmFeatureSupportedFunction(RepositoryService repositoryService, ScmService scmService) {
        this.repositoryService = repositoryService;
        this.scmService = scmService;
    }

    @Override
    public Boolean apply(Object... objects) {
        SoyArgumentUtils.ensureArgumentTypeIsOneOf(objects, 0, Repository.class, String.class);

        String feature;
        Repository repository;
        if (objects.length == 2) {
            repository = (Repository) objects[0];
            feature = SoyArgumentUtils.getStringArgument(objects, 1);
        } else {
            repository = repositoryService.getBySlug((String) objects[0], (String) objects[1]);
            feature = SoyArgumentUtils.getStringArgument(objects, 2);
        }

        if (repository == null) {
            throw new IllegalArgumentException("No repository was provided. Checking SCM " +
                    "feature support requires a repository to test against.");
        }

        return scmService.isSupported(repository, ScmFeature.parse(feature));
    }

    @Override
    public String getName() {
        return "isScmFeatureSupported";
    }

    @Override
    public Set<Integer> validArgSizes() {
        return VALID_SIZES;
    }
}
