import fs from 'fs'
import nodemailer from 'nodemailer';
import utils from './publisher-utils.js';

export default class MailNotificationPublisher {

  constructor( config ) {
      this.fs = fs;
      this.log = null;
      this.utils = utils;
      this.config = config;
      this.transport = nodemailer.createTransport(config.nodemailerTransportOptions);
}

  async publish(reportFilePath) {
    console.log("Running MailNotificationPublisher");
    try {
        let logStr = this.fs.readFileSync(reportFilePath, 'utf8');
        if (!logStr){
            throw new Error('Could not read logfile');
        }
        this.log = JSON.parse(logStr);
        if (!this.log.allResults.meta || !this.log.allResults.meta.env){
            throw new Error('Logfile is missing data');
        }
        this.config.mails.forEach(mail => {
          let groupResult = false;
          if (mail.group){
            if (this.log.groupedResults) {
              if (this.log.groupedResults[mail.group]) {
                groupResult = this.log.groupedResults[mail.group];
              } else {
                console.error("MailNotificationPublisher: mail requested on groupedResults: " + mail.group + " but not group not found in the report")
              }
            } else {
              console.error("MailNotificationPublisher: mail requested on groupedResults but not groupedResults exist")
            }
          } else {
            groupResult = this.log.allResults;
          }
          if (groupResult) {
            if (!mail.errorTreshhold || mail.errorTreshhold <= groupResult.total_failures){
              let html_content = '<html><p><a href="' + mail.dashboardLink + '">Link to Dashboard</a></p>'
              let text_content = "Link to Dashboard:" + mail.dashboardLink + "\n"
              if (groupResult.executionLink) {
                  html_content += '<p><a href="' + groupResult.executionLink + '">Link to the execution report</a></p>';
                  text_content += 'Link to the execution report: ' + groupResult.executionLink;
              }
              if (groupResult.total_failures > 0) {
                html_content += '<p>Test counted ' + groupResult.total_failures + ' fails</p>';
                text_content += "\nTest counted " + groupResult.total_failures + ' fails';
              }
              if(groupResult.meta.testedVersion) {
                html_content += '<p>Application version: ' + groupResult.meta.testedVersion + '</p>';
                text_content += "\nApplication version: " + groupResult.meta.testedVersion;
              }
              html_content += '</html>';
              let message = {
                  from: mail.from,
                  to:  mail.to,
                  bcc: mail.bcc,
                  subject: mail.subject + ', failures registered: ' + groupResult.total_failures,
                  text: text_content,
                  html: html_content
              };
              this.transport.sendMail(message, function(err, info) {
                  if (err) {
                  console.log(err)
                  } else {
                  console.log(info);
                  }
              });
            }
          }
        });
    } catch (error) {
        console.error('An error occured in MailNotificationPublisher.publish, error:' + error);
        return;
    }
  }
}
