import {
    ObjectBasedClassSerializationAdapter
} from "../../../ecs/storage/binary/object/ObjectBasedClassSerializationAdapter.js";
import { ParallelBehavior } from "./ParallelBehavior.js";

export class ParallelBehaviorSerializationAdapter extends ObjectBasedClassSerializationAdapter {
    constructor() {
        super();

        this.klass = ParallelBehavior;
        this.version = 0;
    }

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {ParallelBehavior} value
     */
    serialize(buffer, value) {

        buffer.writeUint8(value.getSuccessPolicy());
        buffer.writeUint8(value.getFailurePolicy());

        const children = value.children;

        const n = children.length;

        buffer.writeUintVar(n);

        for (let i = 0; i < n; i++) {
            const behavior = children[i];

            this.objectAdapter.serialize(buffer, behavior);
        }
    }

    /**
     *
     * @param {BinaryBuffer} buffer
     * @param {ParallelBehavior} value
     */
    deserialize(buffer, value) {
        const successPolicy = buffer.readUint8();
        const failurePolicy = buffer.readUint8();

        const count = buffer.readUintVar();

        value.clearChildren();

        for (let i = 0; i < count; i++) {
            /**
             *
             * @type {Behavior}
             */
            const child = this.objectAdapter.deserialize(buffer);

            value.addChild(child);
        }

        value.setFailurePolicy(failurePolicy);
        value.setSuccessPolicy(successPolicy);
    }
}
