package com.atlassian.stash.internal.crowd;

import com.atlassian.bitbucket.util.UserUtils;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nullable;
import java.util.regex.Pattern;

/**
 * Matches attributes of an entity against a filter string using the {@link UserUtils#createNameMatchingPattern(String)}
 */
abstract class NameMatchingFilter<T> extends Filter<T> {

    private final Pattern pattern;

    /**
     * @param crowdControl the {@link com.atlassian.stash.internal.crowd.CrowdControl} bean
     * @param filter the filter transform with {@link UserUtils#createNameMatchingPattern(String)} to match entity attributes against,
     *               or null to allow all values through
     */
    protected NameMatchingFilter(RiotPolice crowdControl, @Nullable String filter) {
        super(crowdControl);
        if (StringUtils.isBlank(filter)) {
            pattern = null;
        } else {
            pattern = UserUtils.createNameMatchingPattern(filter);
        }
    }

    /**
     * @param values the attribute values to test against the filter pattern. {@code null} values are allowed but will
     *               be ignored
     * @return true if the pattern is unset, or the value matches the pattern
     */
    protected boolean filterMatchesOneOf(String... values) {
        if (pattern == null) {
            return true;
        }

        for (String value : values) {
            if (value != null && pattern.matcher(value).find()) {
                return true;
            }
        }

        return false;
    }
}
