import CancelablePromise from 'cancelable-promise';

export default class AbortableRequest {

    timoutId;
    timeoutEnd;


}


const makeCancelable = (promise) => {
    let hasCanceled_ = false;

    const wrappedPromise = new Promise((resolve, reject) => {
        promise.then(
            val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
            error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
        );
    });

    return {
        promise: wrappedPromise,
        cancel() {
            hasCanceled_ = true;
        },
    };
};

export const performCancellableRequest = async (successCallback, abortController) => {
    abortController = abortController ? abortController : new AbortController();
    let timeoutId;
    const promise = new CancelablePromise(resolve => {
        const timeout = Math.random() * 500;
        timeoutId = setTimeout(resolve, timeout);
    }).then(successCallback);

    abortController.signal.onabort = () => {
        clearTimeout(timeoutId);
        promise.cancel();
    };

    return promise;
}

