import TaskGroup from "../../../core/process/task/TaskGroup.js";
import { GridTaskGenerator } from "../GridTaskGenerator.js";

export class GridTaskSequence extends GridTaskGenerator {

    /**
     *
     * @type {GridTaskGenerator[]}
     */
    children = [];

    /**
     *
     * @param {GridTaskGenerator[]} children
     * @returns {GridTaskSequence}
     */
    static from(children) {
        const r = new GridTaskSequence();

        r.children = children;

        return r;
    }

    build(grid, ecd, seed) {
        const children = this.children;
        const n = children.length;

        const tasks = [];

        // Build tasks
        for (let i = 0; i < n; i++) {
            const child = children[i];

            if (child.dependencies.length > 0) {
                throw new Error('Children are not allowed to have dependencies, dependencies are implied by the sequence');
            }

            const task = child.build(grid, ecd, seed);

            if (i > 0) {
                // add dependence on previous task
                const dependency = tasks[i - 1];

                task.addDependency(dependency);
            }

            tasks.push(task);
        }

        return new TaskGroup(tasks, 'Grid Task Sequence');
    }
}
