package com.atlassian.bitbucket.event.project;

import com.atlassian.bitbucket.event.CancelableEvent;
import com.atlassian.bitbucket.i18n.KeyedMessage;
import com.atlassian.bitbucket.project.ProjectService;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.util.CancelState;

import javax.annotation.Nonnull;

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

/**
 /**
 * Event that is raised just before a {@link Project project} is deleted. This event is synchronous, allowing
 * listeners to perform clean up in the same database transaction where the project will be deleted.
 * <p>
 * This event is {@link CancelableEvent cancelable}. A listener may prevent the project from being deleted by
 * {@link #cancel(KeyedMessage) canceling} this event. Throwing an exception <i>will
 * not</i> prevent the project from being deleted; the exception will be logged and ignored.
 *
 * @see ProjectService#delete(Project)
 */
public class ProjectDeletionRequestedEvent extends ProjectEvent implements CancelableEvent {

    private final CancelState cancelState;

    public ProjectDeletionRequestedEvent(@Nonnull Object source, @Nonnull Project project,
                                         @Nonnull CancelState cancelState) {
        super(source, project);

        this.cancelState = checkNotNull(cancelState, "cancelState");
    }

    /**
     * Cancels project deletion, providing a message explaining why.
     *
     * @param message a descriptive message explaining why the operation has been canceled
     */
    @Override
    public void cancel(@Nonnull KeyedMessage message) {
        cancelState.cancel(message);
    }

    /**
     * Retrieves a flag indicating whether project deletion has already been canceled by another listener.
     *
     * @return {@code true} if another listener has already canceled project deletion; otherwise, {@code false}
     */
    @Override
    public boolean isCanceled() {
        return cancelState.isCanceled();
    }
}
