import axios from 'axios';

// sends an email using the BIC service

export default class Mail{

  static readonly address = 'definma@bosch-iot.com';
  static uri: string;
  static auth = {username: '', password: ''};
  static mailPass: string;

  static init() {
    if (process.env.NODE_ENV === 'production') {  // only send mails in production
      this.mailPass = Array(64).fill(0).map(() => Math.floor(Math.random() * 10)).join('');
      this.uri = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.uri;
      this.auth.username = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.username;
      this.auth.password = JSON.parse(process.env.VCAP_SERVICES).Mail[0].credentials.password;
      axios({  // get registered mail addresses
        method: 'get',
        url: this.uri + '/management/userDomainMapping',
        auth: this.auth
      }).then(res => {
        return new Promise(async (resolve, reject) => {
          try {
            if (res.data.addresses.indexOf(this.address) < 0) {  // mail address not registered
              if (res.data.addresses.length) {  // delete wrong registered mail address
                await axios({
                  method: 'delete',
                  url: this.uri + '/management/mailAddresses/' + res.data.addresses[0],
                  auth: this.auth
                });
              }
              await axios({  // register right mail address
                method: 'post',
                url: this.uri + '/management/mailAddresses/' + this.address,
                auth: this.auth
              });
            }
            resolve();
          }
          catch (e) {
            reject(e);
          }
        });
      }).then(() => {
        return axios({  // set new mail password
          method: 'put',
          url: this.uri + '/management/mailAddresses/' + this.address + '/password/' + this.mailPass,
          auth: this.auth
        });
      }).then(() => {  // init done successfully
        console.info('Mail service established successfully');
        this.send('lukas.veit@bosch.com', 'Mail Service started', new Date().toString());
      }).catch(err => {  // anywhere an error occurred
        console.error(`Mail init error: ${err.request.method} ${err.request.path}: ${err.response.status}`,
          err.response.data);
      });
    }
  }

  static send (mailAddress, subject, content, f: (x?) => void = () => {}) {  // callback, executed empty or with error
    if (process.env.NODE_ENV === 'production') {  // only send mails in production
      axios({
        method: 'post',
        url: this.uri + '/email',
        auth: this.auth,
        data: {
          recipients: [{to: mailAddress}],
          subject: {content: subject},
          body: {
            content: content,
            contentType: "text/html"
          },
          from: {
            eMail: this.address,
            password: this.mailPass
          }
        }
      }).then(() => {
        f();
      }).catch((err) => {
        f(err);
      });
    }
    else {  // dev dummy replacement
      console.info('Sending mail to ' + mailAddress + ':  -- ' + subject + ' -- ' + content);
      f();
    }
  }
}
