package com.atlassian.bitbucket.internal.webhook.repository;

import com.atlassian.bitbucket.event.ApplicationEvent;
import com.atlassian.bitbucket.event.repository.RepositoryRefsChangedEvent;
import com.atlassian.bitbucket.repository.RefChange;
import com.atlassian.webhooks.api.register.listener.WebHookListener;
import com.atlassian.webhooks.spi.EventMatcher;

import java.util.Collection;

import static com.atlassian.bitbucket.internal.webhook.repository.RepositoryEventMatcher.matchesScope;

/**
 * Matches {@link RepositoryRefsChangedEvent ref change events} for web hooks. If a repository id or project id were
 * specified during registration, the repository or project the event is related to is also checked.
 */
public class RepositoryRefsChangedEventMatcher implements EventMatcher<ApplicationEvent> {

    @Override
    public boolean matches(ApplicationEvent event, WebHookListener listener) {
        if (!RepositoryRefsChangedEvent.class.isInstance(event)) {
            return false;
        }

        RepositoryRefsChangedEvent refsChangedEvent = RepositoryRefsChangedEvent.class.cast(event);
        Collection<RefChange> changes = refsChangedEvent.getRefChanges();
        //noinspection ConstantConditions
        return changes != null && !changes.isEmpty() &&
                matchesScope(refsChangedEvent.getRepository(), listener.getParameters());
    }
}