"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteXPrv = exports.ReadXPrv = void 0;
const bin_util_1 = require("@ot-builder/bin-util");
const errors_1 = require("@ot-builder/errors");
const ot_ext_private_1 = require("@ot-builder/ot-ext-private");
const primitive_1 = require("@ot-builder/primitive");
const blob_1 = require("./blob");
exports.ReadXPrv = (0, bin_util_1.Read)((view, gOrd) => {
    const magic = view.next(primitive_1.Tag);
    if (magic !== ot_ext_private_1.XPrv.Tag)
        throw errors_1.Errors.FormatNotSupported("ExpPrivateTable::Magic", magic);
    const majorVersion = view.uint16();
    const minorVersion = view.uint16();
    errors_1.Assert.SubVersionSupported("ExtPrivateTable::Version", majorVersion, minorVersion, [0, 1]);
    const table = new ot_ext_private_1.XPrv.Table();
    const pSharedBlob = view.ptr32Nullable();
    const pPerGlyphBlob = view.ptr32Nullable();
    if (pSharedBlob) {
        table.shared = pSharedBlob.next(blob_1.ReadBlob);
    }
    if (pPerGlyphBlob) {
        table.perGlyph = new Map();
        const nRecords = pPerGlyphBlob.uint16();
        for (let id = 0; id < nRecords; id++) {
            const gid = pPerGlyphBlob.uint16();
            const blob = pPerGlyphBlob.ptr32().next(blob_1.ReadBlob);
            table.perGlyph.set(gOrd.at(gid), blob);
        }
    }
    return table;
});
exports.WriteXPrv = (0, bin_util_1.Write)((fr, table, gOrd) => {
    fr.push(primitive_1.Tag, ot_ext_private_1.XPrv.Tag);
    fr.uint16(0).uint16(1); // version
    fr.ptr32(table.shared ? bin_util_1.Frag.from(blob_1.WriteBlob, table.shared) : null);
    if (!table.perGlyph) {
        fr.ptr32(null);
    }
    else {
        const frPerGlyph = new bin_util_1.Frag();
        const mapping = [];
        for (const [g, blob] of table.perGlyph)
            mapping.push([gOrd.reverse(g), blob]);
        mapping.sort((a, b) => a[0] - b[0]);
        frPerGlyph.uint16(mapping.length);
        for (const [gid, blob] of mapping) {
            frPerGlyph.uint16(gid).ptr32(bin_util_1.Frag.from(blob_1.WriteBlob, blob));
        }
        fr.ptr32(frPerGlyph);
    }
});
//# sourceMappingURL=index.js.map