package com.atlassian.bitbucket.event.repository;

import com.atlassian.bitbucket.event.CancelableEvent;
import com.atlassian.bitbucket.i18n.KeyedMessage;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.RepositoryService;
import com.atlassian.bitbucket.util.CancelState;

import javax.annotation.Nonnull;

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

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

    private final CancelState cancelState;

    public RepositoryDeletionRequestedEvent(@Nonnull Object source, @Nonnull Repository repository,
                                            @Nonnull CancelState cancelState) {
        super(source, repository);

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

    /**
     * Cancels repository 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 repository deletion has already been canceled by another listener.
     *
     * @return {@code true} if another listener has already canceled repository deletion; otherwise, {@code false}
     */
    @Override
    public boolean isCanceled() {
        return cancelState.isCanceled();
    }
}
