/**
 * One-time generator for resources/assets/js/jspdf-dejavu-fonts.js.
 *
 * Reads the DejaVuSans regular + bold TTFs from the dejavu-fonts-ttf npm
 * package, base64-encodes them, and writes out a self-contained JS file
 * that registers both faces into jsPDF's virtual filesystem. This lets the
 * bootstrap-table export button produce PDFs with Cyrillic (and every other
 * Unicode range DejaVuSans covers) instead of the Helvetica-only garbage
 * jsPDF falls back to by default.
 *
 * Run this once when the source TTFs change:
 *
 *     node resources/assets/js/build-jspdf-dejavu-fonts.js
 *
 * Then commit the generated resources/assets/js/jspdf-dejavu-fonts.js.
 * The generated file is bundled by webpack.mix.js right after jspdf.umd.min.js.
 */

const fs = require('fs');
const path = require('path');

const outPath = path.join(__dirname, 'jspdf-dejavu-fonts.js');
const ttfDir = path.join(__dirname, '..', '..', '..', 'node_modules', 'dejavu-fonts-ttf', 'ttf');

// jsPDF/autotable looks fonts up by (name, style) where `style` is one of
// 'normal' | 'italic' | 'bold' | 'bolditalic'. Registering the bold face
// with `style: 'normal', weight: 'bold'` (jsPDF's 4-arg addFont form) makes
// autotable's `getFont('DejaVuSans', 'bold')` MISS — it looks up by the
// style slot, not the weight slot. So the second face has to declare
// `style: 'bold'` directly. If you add italic/bolditalic TTFs in the
// future, list them here the same way (`style: 'italic'`, etc.).
const faces = [
    { file: 'DejaVuSans.ttf', style: 'normal' },
    { file: 'DejaVuSans-Bold.ttf', style: 'bold' },
];

const registrations = faces.map(({ file, style }) => {
    const buf = fs.readFileSync(path.join(ttfDir, file));
    const b64 = buf.toString('base64');
    return `        this.addFileToVFS(${JSON.stringify(file)}, ${JSON.stringify(b64)});\n` +
           `        this.addFont(${JSON.stringify(file)}, 'DejaVuSans', ${JSON.stringify(style)});`;
}).join('\n');

const out = `/**
 * DejaVuSans (regular + bold) registered into jsPDF's virtual filesystem so
 * PDF exports render Unicode text (Cyrillic, Greek, Hebrew, Arabic, and every
 * other range DejaVuSans covers) instead of Helvetica-fallback garbage.
 *
 * Auto-generated by resources/assets/js/build-jspdf-dejavu-fonts.js. Do not
 * edit by hand; re-run the generator if the source fonts change.
 *
 * License: DejaVu is public-domain / Bitstream Vera license. See
 * https://dejavu-fonts.github.io/License.html.
 */
(function (global) {
    var jsPDF = global.jspdf && global.jspdf.jsPDF ? global.jspdf.jsPDF : global.jsPDF;
    if (!jsPDF || !jsPDF.API || !jsPDF.API.events) {
        return;
    }

    jsPDF.API.events.push(['addFonts', function () {
${registrations}
    }]);
})(typeof window !== 'undefined' ? window : globalThis);
`;

fs.writeFileSync(outPath, out);
console.log('Wrote', outPath, '(' + Math.round(out.length / 1024) + ' KB)');
