const {Report, Email} = require('vn-print');

module.exports = Self => {
    Self.printReport = async function(ctx, id, reportName) {
        const args = Object.assign({}, ctx.args);
        const params = {lang: ctx.req.getLocale()};

        delete args.ctx;
        for (const param in args)
            params[param] = args[param];

        const report = new Report(reportName, params);
        const stream = await report.toPdfStream();

        let fileName = `${reportName}`;
        if (id) fileName += `-${id}`;

        return [stream, 'application/pdf', `filename="${fileName}.pdf"`];
    };

    Self.printEmail = async function(ctx, id, templateName) {
        const {accessToken} = ctx.req;
        const args = Object.assign({}, ctx.args);
        const params = {lang: ctx.req.getLocale()};

        delete args.ctx;
        for (const param in args)
            params[param] = args[param];

        params.isPreview = true;
        params.access_token = accessToken.id;

        const report = new Email(templateName, params);
        const html = await report.render();

        let fileName = `${templateName}`;
        if (id) fileName += `-${id}`;

        return [html, 'text/html', `filename=${fileName}.pdf"`];
    };

    Self.sendTemplate = async function(ctx, templateName, force) {
        const args = Object.assign({}, ctx.args);
        const params = {
            recipient: args.recipient,
            lang: ctx.req.getLocale()
        };

        delete args.ctx;
        for (const param in args)
            params[param] = args[param];

        const email = new Email(templateName, params);

        return email.send({force: force});
    };
};