"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteCff2 = void 0;
const bin_util_1 = require("@ot-builder/bin-util");
const errors_1 = require("@ot-builder/errors");
const subroutine_index_1 = require("../char-string/read/subroutine-index");
const write_1 = require("../context/write");
const font_dict_1 = require("../dict/font-dict");
const top_1 = require("../dict/top");
const io_1 = require("../fd-select/io");
const cff2_header_1 = require("../structs/cff2-header");
const cff2_ivs_1 = require("../structs/cff2-ivs");
const shared_1 = require("./shared");
exports.WriteCff2 = (0, bin_util_1.Write)((frag, cff, gOrd, cfg, head, designSpace, stat) => {
    (0, shared_1.cffCleanupUnusedData)(cff);
    const ctx = new write_1.CffWriteContext(cff.version, head.unitsPerEm, !!designSpace, stat);
    const charStringResults = (0, shared_1.buildCharStrings)(cff, cfg, gOrd, ctx);
    const td = setupTopDict(cff, gOrd, charStringResults, ctx, designSpace);
    const fgTop = bin_util_1.Frag.from(top_1.CffTopDictIo, td, ctx, undefined);
    // WRITE!
    frag.push(cff2_header_1.Cff2Header, {
        majorVersion: 2,
        minorVersion: 0,
        headerSize: 5,
        topDictLength: fgTop.size
    });
    frag.embed(fgTop);
    frag.push(subroutine_index_1.CffSubroutineIndex, charStringResults.globalSubroutines, ctx);
    (0, shared_1.cffCleanupUnusedData)(cff);
});
function setupTopDict(cff, gOrd, charStringResults, ctx, designSpace) {
    const td = new top_1.CffTopDictWrite(cff.topDict);
    td.fgCharStrings = bin_util_1.Frag.from(subroutine_index_1.CffSubroutineIndex, charStringResults.charStrings, ctx);
    if (!cff.fdArray)
        throw errors_1.Errors.Cff.ShouldHaveFdArray();
    td.fgFDArray = bin_util_1.Frag.from(font_dict_1.CffFdArrayIo, cff.fdArray, ctx);
    if (cff.fdSelect)
        td.fgFDSelect = bin_util_1.Frag.from(io_1.CffFdSelect, (0, shared_1.getRevFdSelect)(cff, gOrd), ctx);
    else
        td.fgFDSelect = null;
    if (ctx.ivs && designSpace)
        td.fgVarStore = bin_util_1.Frag.from(cff2_ivs_1.Cff2IVS, ctx.ivs, designSpace);
    else
        td.fgVarStore = null;
    return td;
}
//# sourceMappingURL=write-cff2.js.map