import { TaskSignal } from "../TaskSignal.js";
import Task from "../Task.js";

/**
 *
 * @param {Promise} promise
 * @param {string} name
 * @returns {Task}
 */
export function promiseTask(promise, name) {
    let resolved = false;
    let rejected = false;
    let error = null;

    promise.then(function () {
        resolved = true;
    }, function (e) {
        rejected = true;
        error = e;
    });

    function cycle() {
        if (resolved) {
            return TaskSignal.EndSuccess;
        } else if (rejected) {
            throw error;
        } else {
            //give up CPU share
            return TaskSignal.Yield;
        }
    }

    function progress() {
        return resolved ? 1 : 0;
    }

    return new Task({
        name: name,
        cycleFunction: cycle,
        computeProgress: progress
    });
}
