"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var axios = require('axios');

var apiUrl = 'https://api.cloudflare.com/client/v4'; // Endpoint 

var Mailinabox =
/*#__PURE__*/
function () {
  function Mailinabox(config) {
    _classCallCheck(this, Mailinabox);

    this.config = config ? config : {};

    if (!this.config.miabHost) {
      this.config.miabHost = process.env.MIAB_HOST;
      this.config.adminEmail = process.env.MIAB_ADMIN_EMAIL;
      this.config.adminPassword = process.env.MIAB_ADMIN_PASSWORD;
    }
  }

  _createClass(Mailinabox, [{
    key: "init",
    value: function init() {
      if (this.config.arrTokens) {
        this.zones = [];
      }
    }
  }, {
    key: "checkIfParamOk",
    value: function checkIfParamOk() {
      if (!this.config.miabHost || !this.config.adminEmail || !this.config.adminPassword) {
        console.error('Configurazione mancante per il recupero del record DKIM.');
        return false;
      }

      return true;
    } // Funzione per ottenere il record DKIM

  }, {
    key: "getDKIMRecord",
    value: function getDKIMRecord(domain) {
      var url, auth, response, records, dkimRecord, pattern, match;
      return regeneratorRuntime.async(function getDKIMRecord$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (this.checkIfParamOk()) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return", '');

            case 2:
              url = "https://".concat(this.config.miabHost, "/admin/dns/zonefile/").concat(domain);
              auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64');
              _context.prev = 4;
              _context.next = 7;
              return regeneratorRuntime.awrap(axios.get(url, {
                headers: {
                  'Authorization': "Basic ".concat(auth)
                }
              }));

            case 7:
              response = _context.sent;
              // console.log(`Record DNS esterni per ${config.domain}:`);
              // Analizza la risposta per estrarre i record DNS
              records = response.data.split('\n').filter(function (line) {
                return line.trim() !== '' && !line.startsWith(';');
              }).map(function (line) {
                return line.trim();
              }); // Trova e stampa il record DKIM

              dkimRecord = records.find(function (record) {
                return record.includes('mail._domainkey');
              });

              if (!dkimRecord) {
                _context.next = 18;
                break;
              }

              pattern = /p=([A-Za-z0-9+/=]+)(?:"\s*"([A-Za-z0-9+/=]+))?/; // Esegui la ricerca

              match = dkimRecord.match(pattern);

              if (!match) {
                _context.next = 17;
                break;
              }

              return _context.abrupt("return", match[1] + (match[2] || ''));

            case 17:
              console.log('Record DKIM non trovato.');

            case 18:
              return _context.abrupt("return", '');

            case 21:
              _context.prev = 21;
              _context.t0 = _context["catch"](4);
              console.error('Errore nel recupero del record DKIM:', _context.t0.message);

              if (_context.t0.response) {
                console.error('Dettagli errore:', _context.t0.response.data);
              }

            case 25:
              return _context.abrupt("return", '');

            case 26:
            case "end":
              return _context.stop();
          }
        }
      }, null, this, [[4, 21]]);
    }
  }, {
    key: "MIAB_getEmails",
    value: function MIAB_getEmails(myrec) {
      var url, auth, response, records;
      return regeneratorRuntime.async(function MIAB_getEmails$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(!this.checkIfParamOk() || !myrec.domain)) {
                _context2.next = 2;
                break;
              }

              return _context2.abrupt("return");

            case 2:
              url = "https://".concat(this.config.miabHost, "/admin/mail/users?format=text");
              auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64');
              _context2.prev = 4;
              _context2.next = 7;
              return regeneratorRuntime.awrap(axios.get(url, {
                headers: {
                  'Authorization': "Basic ".concat(auth)
                }
              }));

            case 7:
              response = _context2.sent;
              records = response.data.split('\n').filter(function (line) {
                return line.trim() !== '' && line.indexOf(myrec.domain) > -1;
              }).map(function (line) {
                return line.trim();
              });
              return _context2.abrupt("return", records);

            case 12:
              _context2.prev = 12;
              _context2.t0 = _context2["catch"](4);
              console.error('Errore nel recupero delle Email ', _context2.t0.message);

              if (_context2.t0.response) {
                console.error('Dettagli errore:', _context2.t0.response.data);
              }

            case 16:
              return _context2.abrupt("return", '');

            case 17:
            case "end":
              return _context2.stop();
          }
        }
      }, null, this, [[4, 12]]);
    }
  }, {
    key: "removeEmail",
    value: function removeEmail(myrec) {
      var url, auth, myrecout, response, ris;
      return regeneratorRuntime.async(function removeEmail$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              if (!(!this.checkIfParamOk() || !myrec.email)) {
                _context3.next = 2;
                break;
              }

              return _context3.abrupt("return");

            case 2:
              url = "https://".concat(this.config.miabHost, "/admin/mail/users/remove");
              auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64');
              _context3.prev = 4;
              myrecout = "email=".concat(myrec.email);
              _context3.next = 8;
              return regeneratorRuntime.awrap(axios.post(url, myrecout, {
                headers: {
                  'Authorization': "Basic ".concat(auth)
                }
              }));

            case 8:
              response = _context3.sent;
              ris = response.data;
              return _context3.abrupt("return", ris);

            case 13:
              _context3.prev = 13;
              _context3.t0 = _context3["catch"](4);
              console.error('Errore nella cancellazione della Email ' + record.email, _context3.t0.message);

              if (_context3.t0.response) {
                console.error('Dettagli errore:', _context3.t0.response.data);
              }

            case 17:
              return _context3.abrupt("return", '');

            case 18:
            case "end":
              return _context3.stop();
          }
        }
      }, null, this, [[4, 13]]);
    }
  }, {
    key: "addEmail",
    value: function addEmail(myrec) {
      var url, auth, privileges, myrecout, response, ris;
      return regeneratorRuntime.async(function addEmail$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              if (!(!this.checkIfParamOk() || !myrec.email)) {
                _context4.next = 2;
                break;
              }

              return _context4.abrupt("return");

            case 2:
              url = "https://".concat(this.config.miabHost, "/admin/mail/users/add");
              auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64');
              _context4.prev = 4;
              privileges = myrec.privileges ? 'admin' : '';
              myrecout = "email=".concat(myrec.email, "&password=").concat(myrec.pwd, "&privileges=\"").concat(privileges, "\"");
              _context4.next = 9;
              return regeneratorRuntime.awrap(axios.post(url, myrecout, {
                headers: {
                  'Authorization': "Basic ".concat(auth)
                }
              }));

            case 9:
              response = _context4.sent;
              ris = response.data;
              return _context4.abrupt("return", ris);

            case 14:
              _context4.prev = 14;
              _context4.t0 = _context4["catch"](4);
              console.error('Errore nella creazione della Email ' + record.email, _context4.t0.message);

              if (_context4.t0.response) {
                console.error('Dettagli errore:', _context4.t0.response.data);
              }

            case 18:
              return _context4.abrupt("return", '');

            case 19:
            case "end":
              return _context4.stop();
          }
        }
      }, null, this, [[4, 14]]);
    }
  }, {
    key: "setMailUserPassword",
    value: function setMailUserPassword(myrec) {
      var url, auth, data, response, ris;
      return regeneratorRuntime.async(function setMailUserPassword$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              if (!(!this.checkIfParamOk() || !myrec.email)) {
                _context5.next = 2;
                break;
              }

              return _context5.abrupt("return");

            case 2:
              url = "https://".concat(this.config.miabHost, "/admin/mail/users/password");
              auth = Buffer.from("".concat(this.config.adminEmail, ":").concat(this.config.adminPassword)).toString('base64');
              _context5.prev = 4;
              data = "email=".concat(myrec.email, "&password=").concat(myrec.pwd);
              _context5.next = 8;
              return regeneratorRuntime.awrap(axios.post(url, data, {
                headers: {
                  'Authorization': "Basic ".concat(auth),
                  'Content-Type': 'application/x-www-form-urlencoded'
                }
              }));

            case 8:
              response = _context5.sent;
              ris = '';

              if (response.status === 200) {
                ris = "Password cambiata con successo per ".concat(myrec.email);
              } else {
                ris = "Errore nel cambio password per ".concat(myrec.email);
              }

              return _context5.abrupt("return", ris);

            case 14:
              _context5.prev = 14;
              _context5.t0 = _context5["catch"](4);
              console.error('Errore nella creazione della Email ' + record.email, _context5.t0.message);

              if (_context5.t0.response) {
                console.error('Dettagli errore:', _context5.t0.response.data);
              }

            case 18:
              return _context5.abrupt("return", '');

            case 19:
            case "end":
              return _context5.stop();
          }
        }
      }, null, this, [[4, 14]]);
    }
  }]);

  return Mailinabox;
}();

module.exports = Mailinabox;