"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlyphSharer = void 0;
exports.shareGlyphSet = shareGlyphSet;
const Rectify = require("@ot-builder/rectify");
const design_unifier_1 = require("../support/design-unifier");
const glyph_hasher_1 = require("../support/share-glyph-set/glyph-hasher");
class GlyphSharer {
    constructor(gsf) {
        this.gsf = gsf;
        this.session = new design_unifier_1.DesignUnifierSession();
        this.sharedGs = new glyph_hasher_1.SharedGlyphStore();
        this.fonts = [];
        this.fontUnificationResults = [];
    }
    addFont(inputFont) {
        if (this.fonts.length > 0)
            (0, design_unifier_1.unifyDesignSpacesImpl)(this.session, this.fonts[0], inputFont);
        const ur = unifyGlyphByHash(inputFont, this.gsf, this.session, this.sharedGs, this.fonts.length);
        this.fontUnificationResults.push(ur);
        this.fonts.push(inputFont);
    }
    unifyGlyphList() {
        for (const font of this.fonts) {
            font.glyphs = this.gsf.createStoreFromList(this.sharedGs.decideOrder());
        }
    }
    getGlyphList() {
        return Array.from(this.sharedGs.decideOrder());
    }
}
exports.GlyphSharer = GlyphSharer;
function shareGlyphSet(fonts, gsf, options = { unifyGlyphList: false }) {
    const sharer = new GlyphSharer(gsf);
    for (const font of fonts)
        sharer.addFont(font);
    if (options.unifyGlyphList)
        sharer.unifyGlyphList();
}
function unifyGlyphByHash(font, gsf, session, sharedGs, id) {
    const hasher = new glyph_hasher_1.GlyphHasher(session);
    const gOrd = font.glyphs.decideOrder();
    const sharing = new glyph_hasher_1.GlyphSharingRectifier(sharedGs);
    const result = [];
    const originalNames = new WeakMap();
    for (let gid = 0; gid < gOrd.length; gid++) {
        const g = gOrd.at(gid);
        const hash = hasher.compute(g);
        const sharedGlyph = sharing.put(g, hash, id, gid);
        result[gid] = sharedGlyph;
        if (gid && g.name)
            originalNames.set(sharedGlyph, g.name);
    }
    Rectify.inPlaceRectifyFontGlyphReferences(sharing, font);
    font.glyphs = gsf.createStoreFromList(result);
    return { originalNames };
}
//# sourceMappingURL=share-glyph-set.js.map