import fs from 'fs'
import path from 'path'
import ElasticsearchService from '../services/elasticsearch-service.js'
import PublisherUtils from '../reporter/publishers/publisher-utils.js'
import nodemailer from 'nodemailer'
export default class MonitorMonitor {

  constructor(config) {
    this.fs = fs;
    this.path = path;

    this.transport = nodemailer.createTransport(config.nodemailerTransportOptions);
    this.config = config;
  }

  async check() {
    let promises = [];
    this.config.checkSources.forEach(checkSource => {
      if (checkSource.type === "es") {
        let elasticsearch = new ElasticsearchService(checkSource.sourceConfig);
        checkSource.checks.forEach(check => {
          if (check.type === "recent-entry") {
            promises.push(new Promise(async (resolve) => {
              let subject = "";
              let html_content = '<br><a href="' + check.dashboardLink + '">Link to Dashboard</a></p></html>'
              let text_content = "\nDashboard concerned: " + check.dashboardLink;
              try {
                await elasticsearch.search(check.index, 1, check.query, check.sort).then((result) => {
                  if (result && Array.isArray(result) && result.length > 0 && result[0]._source && result[0]._source.start) {
                    let timeLimit = Date.now() - check.moreThen * 60 * 1000;

                    if (result[0]._source.start < timeLimit) {
                      let registeredDate = new Date(result[0]._source.start);
                      subject = check.monitoredSystem + " HAS ISSUE, PLEASE CHECK";
                      html_content = "<html><p>Last registered " + check.monitoredSystem + " result is older then " + check.moreThen + " minutes " +
                        "<br>last result was from test that started at: " + PublisherUtils.getDateAndTime(registeredDate) +
                        "<br>There might be a problem with the monitor" + html_content;
                      text_content = "Last registered " + check.monitoredSystem + " result is older then " + check.moreThen + " minutes " +
                        "\nlast result was from test that started at: " + PublisherUtils.getDateAndTime(registeredDate) +
                        "\nThere might be a problem with the monitor" + text_content;
                    }
                  } else {
                    subject = check.monitoredSystem + " HAS ISSUE, PLEASE CHECK";
                    html_content = "<html><p>Could not retrieve any recent result from ES for the " + check.monitoredSystem +
                      "<br>There might be a problem with elasticsearch" + html_content;
                    text_content = "Could not retrieve any recent result from ES for the " + check.monitoredSystem +
                      "\nThere might be a problem with elasticsearch" + text_content;
                  }
                })
              } catch (error) {
                subject = "Monitor on " + check.monitoredSystem + " HAS ISSUE, PLEASE CHECK";
                html_content = "<html><p>Monitor-monitor had error while retrieving result from ES for the " + check.monitoredSystem +
                  "<br>There might be a problem with elasticsearch or with the Monitor-monitor code/settings" + html_content;
                text_content = "Monitor-monitor had error while retrieving result from ES for the " + check.monitoredSystem +
                  "\nThere might be a problem with elasticsearch or with the Monitor-monitor code/settings" + text_content;
              }
              if (subject !== "") {
                check.mails.forEach(mail => {
                  let message = {
                    from: mail.from,
                    to: mail.to,
                    bcc: mail.bcc,
                    subject: subject,
                    text: text_content,
                    html: html_content
                  };
                  this.transport.sendMail(message, function (err, info) {
                    if (err) {
                      console.log(err)
                    }
                  });
                });
              }
              resolve();
            }))
          }
        });
      }
    });
    await promises;
  }
}
