const path = require('path');
const smtp = require('./smtp');
const config = require('./config');
const Component = require('./component');
const Report = require('./report');

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

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

        this.args = args;
    }

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

    async getSubject() {
        const component = await this.component();
        let locale = this.args.auth.locale;

        if (this.args.recipientId)
            locale = await component.getLocale(this.args.recipientId);

        const messages = this.locale.messages;
        const userTranslations = messages[locale];

        if (!userTranslations) {
            const fallbackLocale = config.i18n.fallbackLocale;

            return messages[fallbackLocale].subject;
        }

        return userTranslations.subject;
    }

    async send() {
        const instance = this.build();
        const rendered = await this.render();
        const attachments = [];
        const getAttachments = async(componentPath, files) => {
            for (file of files) {
                const fileCopy = Object.assign({}, file);
                if (fileCopy.cid) {
                    const templatePath = `${componentPath}/${file.path}`;
                    const fullFilePath = path.resolve(__dirname, templatePath);

                    fileCopy.path = path.resolve(__dirname, fullFilePath);
                } else {
                    const reportName = fileCopy.filename.replace('.pdf', '');
                    const report = new Report(reportName, this.args);
                    fileCopy.content = await report.toPdfStream();
                }

                attachments.push(fileCopy);
            }
        };

        if (instance.components) {
            const components = instance.components;
            for (let componentName in components) {
                const component = components[componentName];
                const componentPath = `./components/${componentName}`;
                await getAttachments(componentPath, component.attachments);
            }
        }

        if (this.attachments)
            await getAttachments(this.path, this.attachments);

        const localeSubject = await this.getSubject();
        const replyTo = this.args.replyTo || this.args.auth.email;
        const options = {
            to: this.args.recipient,
            replyTo: replyTo,
            subject: localeSubject,
            html: rendered,
            attachments: attachments
        };

        return smtp.send(options);
    }
}

module.exports = Email;