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

/**
 *
 * @param {Future} future
 * @param {String} name
 * @returns {Task}
 */
export function futureTask(future, name) {
    if (typeof future.resolve !== 'function') {
        // Not a future
        throw new Error("No resolve function on the supplied object");
    }

    let resolved = false;
    let rejected = false;
    let error = null;

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

    function cycle() {
        future.resolve();
        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
    });
}
