package com.atlassian.bitbucket.hook;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.Function;

/**
 * A service which handles the management of hook requests. It allows SCM providers to register hosting
 * requests with Stash and allow the SCM layer to callback to Stash via a socket
 */
public interface HookService {

    /**
     * Register a hosting request with the hook service. It is the responsibility of the SCM provider to
     * call {@link HookRequestHandle#close()} when the request is complete.
     * It is suggested for implementers to use {@link #doWithHookRequest(int, java.util.function.Function)}
     * if possible as this will clean up the request for the callee
     *
     * @param repositoryId the id of the repository the hosting request is for
     * @return a handle for the HookRequest.
     */
    @Nonnull
    HookRequestHandle registerRequest(int repositoryId);

    /**
     * Perform an operation with a hook request
     * @param repositoryId the id of the repository the hosting request is for
     * @param callback a callback which will handle the operation
     * @param <T> the return type of the callback
     * @return the value returned from the callback
     */
    @Nullable
    <T> T doWithHookRequest(int repositoryId, @Nonnull Function<HookRequestHandle, T> callback);
}
