package com.atlassian.bitbucket.internal.branch.model.restriction.matcher;

import com.atlassian.bitbucket.branch.model.BranchClassifier;
import com.atlassian.bitbucket.branch.model.BranchModel;
import com.atlassian.bitbucket.branch.model.BranchType;
import com.atlassian.bitbucket.internal.branch.model.restriction.type.ModelCategoryMatcherType;
import com.atlassian.bitbucket.repository.Branch;
import com.atlassian.bitbucket.repository.MinimalRef;
import com.atlassian.bitbucket.repository.SimpleBranch;
import com.atlassian.bitbucket.repository.ref.restriction.AbstractRefMatcher;

import javax.annotation.Nonnull;

public class ModelCategoryMatcher extends AbstractRefMatcher {

    private final BranchClassifier classifier;
    private final String displayId;

    public ModelCategoryMatcher(BranchType branchType, BranchModel model) {
        super(ModelCategoryMatcherType.getInstance(), branchType.getId());
        this.displayId = branchType.getDisplayName();

        classifier = model.getClassifier();
    }

    @Nonnull
    @Override
    public String getDisplayId() {
        return displayId;
    }

    @Override
    public boolean matches(@Nonnull MinimalRef ref) {
        Branch branch = new SimpleBranch.Builder()
                .id(ref.getId())
                .displayId(ref.getDisplayId())
                .build();
        BranchType type = classifier.getType(branch);
        return type != null && type.getId().equals(getId());
    }
}
