package com.atlassian.stash.internal.repository.ref.restriction.provider;

import com.atlassian.bitbucket.repository.RefService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.ResolveRefRequest;
import com.atlassian.bitbucket.repository.StandardRefType;
import com.atlassian.bitbucket.repository.ref.restriction.RefMatcher;
import com.atlassian.bitbucket.repository.ref.restriction.RefMatcherProvider;
import com.atlassian.bitbucket.repository.ref.restriction.RefMatcherType;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.atlassian.stash.internal.repository.ref.restriction.RestrictionConstants;

import javax.annotation.Nonnull;

public class BranchMatcherProvider implements RefMatcherProvider {

    private final boolean caseInsensitive;
    private final RefService refService;

    public BranchMatcherProvider(ApplicationPropertiesService propertiesService,
                                 RefService refService) {
        this.refService = refService;

        caseInsensitive = propertiesService.getPluginProperty(RestrictionConstants.PROPERTY_CASE_INSENSITIVE, true);
    }

    @Override
    public RefMatcher create(@Nonnull Repository repository, @Nonnull String value) {
        return new BranchMatcher(value, caseInsensitive,
                () -> refService.resolveRef(new ResolveRefRequest.Builder(repository)
                        .refId(value)
                        .type(StandardRefType.BRANCH)
                        .build()));
    }

    @Nonnull
    @Override
    public RefMatcherType getType() {
        return BranchRestrictionType.getInstance();
    }
}
