"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pdf = void 0;
const fonts_1 = require("./fonts");
const headless_pool_for_process_1 = require("./headless-pool-for-process");
const headless_model_1 = require("./headless-model");
const protocol = 'http';
const host = 'localhost';
const path = '/internal-process-service-view';
const pdf = async ({ id = '', model = null, data = null, width: w = 0, height: h = 0, options = {}, context = {} } = {}) => {
    const browser = (await (0, headless_pool_for_process_1.getHeadlessPool)().acquire());
    if (!browser) {
        return;
    }
    const { domain, user } = context.state;
    var { model, base } = await (0, headless_model_1.headlessModel)({ domain, id, model });
    model.fonts = await (0, fonts_1.fonts)();
    let { width, height } = model;
    width = Number(width);
    height = Number(height);
    if (!w) {
        w = width;
    }
    if (!h) {
        h = height;
    }
    let ratio = Math.min(w / width, h / height);
    width = Math.floor(width * ratio);
    height = Math.floor(height * ratio);
    const port = process.env.PORT ? `:${process.env.PORT}` : '';
    const url = `${protocol}://${host}${port}${path}`;
    const page = await browser.newPage();
    try {
        /* @remember-me width, height should be a integer */
        await page.setViewport({ width, height });
        await page.setRequestInterception(true);
        page.on('console', msg => {
            console.log(`[browser ${msg._type}] ${msg._text}`);
            for (let i = 0; i < msg.args().length; ++i)
                console.log(`${i}: ${msg.args()[i]}`);
        });
        const token = await (user === null || user === void 0 ? void 0 : user.sign()); // TODO improve performance
        page.on('request', request => {
            if (request.url() === url) {
                request.continue({
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-things-factory-domain': domain === null || domain === void 0 ? void 0 : domain.subdomain,
                        Authorization: 'Bearer ' + token
                    },
                    postData: JSON.stringify({
                        model,
                        base
                    })
                });
            }
            else if (request.url().startsWith(`${protocol}://${host}${port}`)) {
                request.continue({
                    headers: Object.assign(Object.assign({}, request.headers()), { 'x-things-factory-domain': domain === null || domain === void 0 ? void 0 : domain.subdomain, Authorization: 'Bearer ' + token })
                });
            }
            else {
                request.continue();
            }
        });
        await page.goto(url);
        await page.evaluate(async (data) => {
            if (data) {
                // @ts-ignore
                s.data = data;
            }
            // data 주입 후 강제 지연시킴.
            return new Promise(resolve => {
                // @ts-ignore
                requestAnimationFrame(() => resolve());
            });
        }, data);
        const pdf = await page.pdf(Object.assign({ format: 'A4' }, options));
    }
    catch (error) {
        console.log(error);
    }
    finally {
        page.close();
        (0, headless_pool_for_process_1.getHeadlessPool)().release(browser);
    }
    return exports.pdf;
};
exports.pdf = pdf;
//# sourceMappingURL=pdf.js.map