package com.atlassian.stash.browser.cancel;

import com.atlassian.bitbucket.event.project.ProjectCreationRequestedEvent;
import com.atlassian.bitbucket.event.pull.PullRequestOpenRequestedEvent;
import com.atlassian.bitbucket.event.repository.RepositoryCreationRequestedEvent;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.event.api.EventListener;

import static org.apache.commons.lang3.StringUtils.trimToEmpty;

/**
 * Cancels events in projects/repositories with special names.
 * <p>
 * This listener cancels events for:
 * <ul>
 *     <li>{@code ProjectListTest.testCreateCancellation()}</li>
 *     <li>{@code PullRequestCreateTest.testCreateCancellation()}</li>
 *     <li>{@code RepositoryCreateTest.testCreateCancellation()}</li>
 * </ul>
 */
public class CancelableEventTestingListener {

    private I18nService i18nService;

    public CancelableEventTestingListener(I18nService i18nService) {
        this.i18nService = i18nService;
    }

    @EventListener
    public void onProjectCreationRequested(ProjectCreationRequestedEvent event) {
        Project project = event.getProject();
        if ("CANCELME".equals(project.getKey())) {
            event.cancel(i18nService.getKeyedText("bitbucket.test.browser.cancel.project",
                    "Testing project creation cancellation."));
        }
    }

    @EventListener
    public void onPullRequestOpenRequested(PullRequestOpenRequestedEvent event) {
        PullRequest pullRequest = event.getPullRequest();
        if (trimToEmpty(pullRequest.getTitle()).contains("***CANCELME***")
                && trimToEmpty(pullRequest.getDescription()).contains("***cancelme***")) {
            event.cancel(i18nService.getKeyedText("bitbucket.test.browser.cancel.pullrequest",
                    "Testing pull request open cancellation."));
        }
    }

    @EventListener
    public void onRepositoryCreationRequested(RepositoryCreationRequestedEvent event) {
        Repository repository = event.getRepository();
        if ("cancelme".equals(repository.getSlug())) {
            event.cancel(i18nService.getKeyedText("bitbucket.test.browser.cancel.repository",
                    "Testing repository creation cancellation."));
        }
    }
}
