"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OtStandardGlyphNamer = void 0;
const AglfnData = require("aglfn");
const AglfnMap = new Map(AglfnData.map(x => [parseInt(x.unicodeValue, 16), x.glyphName]));
class OtStandardGlyphNamer {
    constructor() {
        this.existingNames = new Set();
    }
    avoidCollide(name) {
        if (!this.existingNames.has(name)) {
            this.existingNames.add(name);
            return name;
        }
        let suffix = 2;
        for (;;) {
            const amendedName = name + "." + suffix;
            if (!this.existingNames.has(amendedName)) {
                this.existingNames.add(amendedName);
                return name;
            }
            suffix += 1;
        }
    }
    nameByPost(source, gid, glyph) {
        if (!source.post)
            return null;
        return source.post.getName(glyph);
    }
    nameByCff(source, gid, glyph) {
        if (!source.cff)
            return null;
        return source.cff.getName(glyph);
    }
    formatHex(code) {
        let hex = code.toString(16).toUpperCase();
        while (hex.length < 4)
            hex = "0" + hex;
        return hex;
    }
    nameByEncoding(source, gid, glyph) {
        if (!source.encoding)
            return null;
        const code = source.encoding.getIndex(glyph);
        if (code != null) {
            const aglfnName = AglfnMap.get(code);
            if (aglfnName)
                return aglfnName;
            return "uni" + this.formatHex(code);
        }
        const variantCode = source.encoding.getVariantIndex(glyph);
        if (variantCode && variantCode.length) {
            return "uni" + variantCode.map(k => this.formatHex(k)).join("_");
        }
        return null;
    }
    nameByGid(source, gid, glyph) {
        return `.gid${gid}`;
    }
    nameGlyph(source, gid, glyph) {
        if (gid === 0)
            return `.notdef`;
        return this.avoidCollide(this.nameByPost(source, gid, glyph) ||
            this.nameByCff(source, gid, glyph) ||
            this.nameByEncoding(source, gid, glyph) ||
            this.nameByGid(source, gid, glyph));
    }
}
exports.OtStandardGlyphNamer = OtStandardGlyphNamer;
//# sourceMappingURL=index.js.map