import { Action } from "./Action.js";

/**
 * @template CTX
 */
export class ActionGroup extends Action {

    /**
     * @private
     * @type {Action[]}
     */
    members = [];

    /**
     * @template T
     * @param {Action<T>[]} actions
     * @returns {ActionGroup<T>}
     */
    static from(actions) {
        const r = new ActionGroup();

        r.members = actions;

        return r;
    }

    computeByteSize() {
        let result = 0;

        const members = this.members;
        const n = members.length;
        for (let i = 0; i < n; i++) {
            const action = members[i];

            result += action.computeByteSize();
        }

        return result;
    }

    async apply(context) {
        const members = this.members;
        const n = members.length;
        for (let i = 0; i < n; i++) {
            const action = members[i];

            await action.apply(context);
        }
    }

    async revert(context) {
        const members = this.members;
        const n = members.length;

        for (let i = n - 1; i >= 0; i--) {
            const action = members[i];

            await action.revert(context);
        }
    }
}
