"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CffWriteIndex = void 0;
const bin_util_1 = require("@ot-builder/bin-util");
const errors_1 = require("@ot-builder/errors");
const index_count_1 = require("../structs/index.count");
const off_size_1 = require("../structs/off-size");
const offset_1 = require("../structs/offset");
class CffWriteIndex {
    constructor(writeItem) {
        this.writeItem = writeItem;
    }
    collectOffsets(items, context) {
        errors_1.Assert.NoGap("CFF Index items", items);
        let dataSize = 0;
        const offsets = [];
        const frags = [];
        for (let index = 0; index < items.length; index++) {
            offsets.push(dataSize);
            const fragItem = new bin_util_1.Frag().push(this.writeItem, items[index], context, index);
            dataSize += fragItem.size;
            frags.push(fragItem);
        }
        offsets.push(dataSize);
        return { dataSize, offsets, frags };
    }
    offsetSize(dataSize) {
        return dataSize < 0x100 ? 1 : dataSize < 0x10000 ? 2 : dataSize < 0x1000000 ? 3 : 4;
    }
    write(frag, items, context) {
        errors_1.Assert.NoGap("CFF Index items", items);
        frag.push(index_count_1.CffIndexCount, items.length, context.version); // Item count
        if (!items.length)
            return; // Exit if index is empty
        const { dataSize, offsets, frags } = this.collectOffsets(items, context);
        const offSize = this.offsetSize(dataSize);
        frag.push(off_size_1.CffOffSize, offSize);
        for (const item of offsets)
            frag.push(offset_1.CffOffset, item, offSize);
        for (const frItem of frags)
            frag.embed(frItem);
    }
}
exports.CffWriteIndex = CffWriteIndex;
//# sourceMappingURL=write.js.map