const log = () => {}; // console.log
const start = Date.now();
log(`${Date.now() - start} worker start`);
importScripts(`pdfmake.min.js`, `vfs_fonts.js`);
log(`${Date.now() - start} worker imported scripts`);

pdfMake.vfs = pdfMake_vfs;
pdfMake.fonts = {
    freeSerif: {
        normal: 'TeXGyreTermesRegular.ttf',
        bold: 'TeXGyreTermesBold.ttf',
        italics: 'TeXGyreTermesItalic.ttf',
        bolditalics: 'TeXGyreTermesBoldItalic.ttf'
    }
}

encoded_keys = ['vLineWidth', 'vLineStyle', 'hLineWidth', 'hLineStyle', 'minRowHeight', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom'];

function decode_content(c) {
    if (Array.isArray(c)) {
        return c.map(el => decode_content(el))
    } else if (typeof c === 'object') {
        const o = {};
        for (const key of Object.keys(c)) {
            o[key] = encoded_keys.includes(key) ? (function(i, node) {return c[key][i === 0 ? 0 : 1]}) : decode_content(c[key]);
        }
        return o;
    } else {
        return c;
    }
}

const promise_count = 2; // worker robi po tyle 'równolegle'
let promises = [];
for (let i = 0; i < promise_count; ++i) promises.push(Promise.resolve(null));
let in_counter = 0;

onmessage = (e) => {
    const counter = in_counter;
    in_counter += 1;
    const last_promise = promises[counter%promise_count];
    promises[counter%promise_count] = new Promise(resolve => {
        last_promise.then(() => {
            log(`${Date.now() - start} worker got message ${counter}`);
            const structure = {
                compress: true,
                content: decode_content(e.data.content),
                defaultStyle: e.data.style,
                footer: (currentPage, pageCount, page_size, empty) => {
                    if (empty === true) return {text: ''};
                    return e.data.static_footer;
                },
                header: (currentPage, pageCount, page_size, empty) => {
                    return (currentPage === 1 || empty === true) ? '' : {
                        text: `- ${currentPage} -`,
                        alignment: 'center',
                        margin: [0, 20]
                    }
                },
                pageMargins: e.data.pageMargins
            };
            log(`${Date.now() - start} worker prepared structure ${counter}`);

            pdfMake.createPdf(structure).getBuffer(result => {
                log(`${Date.now() - start} worker created pdf ${counter}`);
                postMessage({file: e.data.file, content: new Uint8Array(result)});
                resolve(null);
            });
        });
    });
};
log(`${Date.now() - start} worker ready`);
