const fs = require('fs');
const pdf = require('html-pdf');
const path = require('path');
const config = require('./config');
const Component = require('./component');

if (!process.env.OPENSSL_CONF)
    process.env.OPENSSL_CONF = '/etc/ssl/';

class Report extends Component {
    constructor(name, args) {
        super(name);

        this.args = args;
    }

    get path() {
        return `../templates/reports/${this.name}`;
    }

    async toPdfStream() {
        const template = await this.render();
        let options = config.pdf;

        const optionsPath = `${this.path}/options.json`;
        const fullPath = path.resolve(__dirname, optionsPath);
        if (fs.existsSync(fullPath))
            options = Object.assign(options, require(optionsPath));

        return new Promise(resolve => {
            pdf.create(template, options).toStream((err, stream) => {
                resolve(stream);
            });
        });
    }
}

module.exports = Report;