import { assert } from "../../../assert.js";
import { anyOf, equalTo } from "../../../debug/matchers/matchers.js";
import Task from "../Task.js";
import { TaskSignal } from "../TaskSignal.js";

/**
 *
 * @param {string} name
 * @param {Iterator} iterator
 * @param {TaskSignal} [cycle_signal] what to signal at the end of each iteration, Continue will provide better throughput, whereas Yield will produce very low load on the CPU
 * @returns {Task}
 */
export function iteratorTask(name, iterator, cycle_signal = TaskSignal.Continue) {
    assert.defined(iterator, 'iterator');
    assert.notNull(iterator, 'iterator');
    assert.isFunction(iterator.next, 'iterator.next');
    assert.that(cycle_signal, 'cycle_signal', anyOf(equalTo(TaskSignal.Continue), equalTo(TaskSignal.Yield)));

    return new Task({
        name,
        cycleFunction() {
            const next = iterator.next();

            if (next.done) {
                return TaskSignal.EndSuccess
            } else {
                return cycle_signal;
            }
        }
    })
}
