"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CvarIo = void 0;
const errors_1 = require("@ot-builder/errors");
const var_store_1 = require("@ot-builder/var-store");
const variance_1 = require("@ot-builder/variance");
const tvd_access_1 = require("../shared/tvd-access");
exports.CvarIo = {
    read(view, cvt, designSpace) {
        const majorVersion = view.uint16();
        const minorVersion = view.uint16();
        errors_1.Assert.SubVersionSupported("CvarTable", majorVersion, minorVersion, [1, 0]);
        const client = new CvtTvhClient(cvt);
        view.next(var_store_1.TupleVariationRead, client, { designSpace, sharedTuples: [] });
    },
    write(frag, cvt, designSpace, acEmpty) {
        frag.uint16(1).uint16(0);
        const context = {
            designSpace: designSpace,
            forceEmbedPeak: true // This is CVAR so force embedding
        };
        const source = new CvtTupleVariationSource(cvt);
        const tvd = var_store_1.TupleVariationWriteOpt.writeOpt(source, context);
        if (tvd) {
            frag.embed(tvd);
        }
        else {
            // Oops the CVAR table is completely empty
            frag.uint16(0).uint16(0);
            // Tell the outside that we are writing something empty
            if (acEmpty)
                acEmpty.set(true);
        }
    }
};
class CvtTvhClient {
    constructor(cvt) {
        this.dimensions = 1;
        const ms = new variance_1.OtVar.MasterSet();
        this.contours = this.createContours(ms, cvt);
    }
    createContours(ms, cvt) {
        const cs = [];
        for (let cvtId = 0; cvtId < cvt.items.length; cvtId++) {
            cs.push([new CvtTvdAccess(ms, cvt, cvtId)]);
        }
        return cs;
    }
    finish() {
        for (const c of this.contours)
            for (const z of c)
                z.finish();
    }
}
class CvtTvdAccess extends tvd_access_1.CumulativeTvd {
    constructor(ms, cvt, cvtId) {
        super(ms);
        this.cvt = cvt;
        this.cvtId = cvtId;
        this.original = variance_1.OtVar.Ops.originOf(cvt.items[cvtId] || 0);
    }
    finish() {
        const cv = this.cvt.items[this.cvtId] || 0;
        this.cvt.items[this.cvtId] = this.collectTo(cv);
    }
}
class CvtTupleVariationSource {
    constructor(cvt) {
        this.dimensions = 1;
        const cs = [];
        for (const entry of cvt.items)
            cs.push([entry]);
        this.data = cs;
    }
}
//# sourceMappingURL=index.js.map