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

import com.atlassian.bitbucket.repository.MinimalRef;
import com.atlassian.bitbucket.repository.ref.restriction.AbstractRefMatcher;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;

import javax.annotation.Nonnull;

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

public class BranchMatcher extends AbstractRefMatcher {

    private final boolean caseInsensitive;
    private final Supplier<MinimalRef> refResolver;

    public BranchMatcher(String refName, boolean caseInsensitive, Supplier<MinimalRef> refResolver) {
        super(BranchRestrictionType.getInstance(), refName);
        this.caseInsensitive = caseInsensitive;
        this.refResolver = Suppliers.memoize(refResolver);
    }

    @Override
    public boolean isActive() {
        return refResolver.get() != null;
    }

    @Override
    public boolean isCaseInsensitive() {
        return caseInsensitive;
    }

    @Nonnull
    @Override
    public String getDisplayId() {
        MinimalRef resolved = refResolver.get();
        return resolved != null ? resolved.getDisplayId() : getId();
    }

    @Override
    public boolean matches(@Nonnull MinimalRef ref) {
        return getId().equalsIgnoreCase(checkNotNull(ref, "ref").getId());
    }
}
