package com.atlassian.bitbucket.event.project;

import com.atlassian.bitbucket.event.CancelableEvent;
import com.atlassian.bitbucket.i18n.KeyedMessage;
import com.atlassian.bitbucket.project.ProjectCreateRequest;
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;

/**
 * Raised just before a {@link Project project} is created. This event is synchronous, allowing listeners to
 * perform operations in the same database transaction where the project will be created.
 * <p>
 * This event is {@link CancelableEvent cancelable}. A listener may prevent the project from being created by
 * {@link #cancel(KeyedMessage) canceling} this event. Throwing an exception <i>will not</i> prevent the project
 * from being created; the exception will be logged and ignored.
 * <p>
 * Note: The project attached to the event will <i>not</i> have an {@link Project#getId() ID}, as it has not
 * been created yet. Any listener which would like to create associations based on that ID must listen for the
 * {@link ProjectCreatedEvent} instead, which will include it (but will not run in the same transaction).
 * <p>
 * This event is internally audited with a LOW priority
 *
 * @see ProjectService#create(ProjectCreateRequest)
 */
public class ProjectCreationRequestedEvent extends ProjectEvent implements CancelableEvent {

    private final CancelState cancelState;

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

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

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