"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteCff1 = 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 glyph_data_source_1 = require("../charset/glyph-data-source");
const io_1 = require("../charset/io");
const write_1 = require("../context/write");
const font_dict_1 = require("../dict/font-dict");
const top_1 = require("../dict/top");
const io_2 = require("../fd-select/io");
const string_index_1 = require("../strings/string-index");
const cff1_header_1 = require("../structs/cff1-header");
const shared_1 = require("./shared");
exports.WriteCff1 = (0, bin_util_1.Write)((frag, cff, gOrd, cfg, head, stat) => {
    (0, shared_1.cffCleanupUnusedData)(cff);
    const ctx = new write_1.CffWriteContext(cff.version, head.unitsPerEm, false, stat);
    if (!ctx.strings)
        throw errors_1.Errors.Cff.ShouldHaveStrings();
    if (cff.cid && !cff.fdArray)
        throw errors_1.Errors.Cff.ShouldHaveFdArray();
    const charStringResults = (0, shared_1.buildCharStrings)(cff, cfg, gOrd, ctx);
    // Set up top dict
    const td = setupTopDict(cff, gOrd, charStringResults, ctx);
    // WRITE!
    frag.push(cff1_header_1.Cff1Header, {
        majorVersion: 1,
        minorVersion: 0,
        headerSize: 4,
        offSize: 4
    });
    frag.push(string_index_1.CffStringIndex, [cff.postScriptFontName], ctx);
    frag.push(top_1.CffTopDictIndexWrite, td, ctx);
    frag.push(string_index_1.CffStringIndex, ctx.strings.getStringIndexList(), ctx);
    frag.push(subroutine_index_1.CffSubroutineIndex, charStringResults.globalSubroutines, ctx);
    (0, shared_1.cffCleanupUnusedData)(cff);
});
function setupTopDict(cff, gOrd, charStringResults, ctx) {
    const td = new top_1.CffTopDictWrite(cff.topDict);
    if (cff.cid)
        td.cidROS = cff.cid;
    td.fgCharStrings = bin_util_1.Frag.from(subroutine_index_1.CffSubroutineIndex, charStringResults.charStrings, ctx);
    if (cff.fdArray)
        td.fgFDArray = bin_util_1.Frag.from(font_dict_1.CffFdArrayIo, cff.fdArray, ctx);
    else
        td.fgFDArray = null;
    if (cff.fdSelect)
        td.fgFDSelect = bin_util_1.Frag.from(io_2.CffFdSelect, (0, shared_1.getRevFdSelect)(cff, gOrd), ctx);
    else
        td.fgFDSelect = null;
    td.fgVarStore = null;
    if (cff.cid) {
        td.fgCharSet = bin_util_1.Frag.from(io_1.CffCharSet, new glyph_data_source_1.CffCidCharSetSource(ctx, gOrd, cff.cid.mapping), ctx);
    }
    else {
        td.fgCharSet = bin_util_1.Frag.from(io_1.CffCharSet, new glyph_data_source_1.CffGlyphNameCharSetSource(ctx, gOrd), ctx);
    }
    return td;
}
//# sourceMappingURL=write-cff1.js.map