"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EjsAdapter = void 0;
const ejs_1 = require("ejs");
const lodash_1 = require("lodash");
const fs = require("fs");
const path = require("path");
const css_inline_1 = require("@css-inline/css-inline");
class EjsAdapter {
    constructor(config) {
        this.precompiledTemplates = {};
        this.config = {
            inlineCssOptions: {},
            inlineCssEnabled: true,
        };
        Object.assign(this.config, config);
    }
    compile(mail, callback, mailerOptions) {
        const { context, template } = mail.data;
        const templateBaseDir = (0, lodash_1.get)(mailerOptions, 'template.dir', '');
        const templateExt = path.extname(template) || '.ejs';
        let templateName = path.basename(template, path.extname(template));
        const templateDir = path.isAbsolute(template)
            ? path.dirname(template)
            : path.join(templateBaseDir, path.dirname(template));
        const templatePath = path.join(templateDir, templateName + templateExt);
        templateName = path
            .relative(templateBaseDir, templatePath)
            .replace(templateExt, '');
        if (!this.precompiledTemplates[templateName]) {
            try {
                const template = fs.readFileSync(templatePath, 'utf-8');
                this.precompiledTemplates[templateName] = (0, ejs_1.compile)(template, Object.assign(Object.assign({}, (0, lodash_1.get)(mailerOptions, 'template.options', {})), { filename: templatePath }));
            }
            catch (err) {
                return callback(err);
            }
        }
        const rendered = this.precompiledTemplates[templateName](context);
        const render = (html) => {
            if (this.config.inlineCssEnabled) {
                try {
                    mail.data.html = (0, css_inline_1.inline)(html, this.config.inlineCssOptions);
                }
                catch (e) {
                    callback(e);
                }
            }
            else {
                mail.data.html = html;
            }
            return callback();
        };
        if (typeof rendered === 'string') {
            render(rendered);
        }
        else {
            rendered.then(render);
        }
    }
}
exports.EjsAdapter = EjsAdapter;
