const clone = require('clone');
const tv4 = require('tv4');

const Recipient = require('./recipient');

class Email {
  constructor(opt) {
    this.toRecipients = [];
    this.ccRecipients = [];
    this.bccRecipients = [];
    this.sendDate = null;
    this.templateLabel = null;
    this.templateParams = {};
    this.notificationId = null;
    this.immediate = false;
    this.replyTo = null;
    if (opt && opt.details) {
      this.fillObject(clone(opt.details));
    }
  }

  fillObject(opt) {
    if (opt.toRecipients) {
      opt.toRecipients.forEach((toRecipient) => this.toRecipients.push(new Recipient(toRecipient)));
    }
    if (opt.ccRecipients) {
      opt.ccRecipients.forEach((ccRecipient) => this.ccRecipients.push(new Recipient(ccRecipient)));
    }
    if (opt.bccRecipients) {
      opt.bccRecipients.forEach((bccRecipient) => this.bccRecipients.push(new Recipient(bccRecipient)));
    }
    this.sendDate = new Date(opt.sendDate);
    this.templateLabel = opt.templateLabel;
    this.templateParams = opt.templateParams;
    this.notificationId = opt.notificationId || null;
    this.immediate = opt.immediate || false;
    this.replyTo = opt.replyTo || null;
  }

  validate() {
    return tv4.validateMultiple(this, Email.schema());
  }

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'email.schema.json',
      type: 'object',
      properties: {
        toRecipients: {
          type: 'array',
          items: {
            $ref: 'recipient.schema.json',
          },
        },
        ccRecipients: {
          type: 'array',
          items: {
            $ref: 'recipient.schema.json',
          },
        },
        bccRecipients: {
          type: 'array',
          items: {
            $ref: 'recipient.schema.json',
          },
        },
        sendDate: { type: 'object' },
        templateLabel: { type: 'string' },
        templateParams: { type: 'object' },
        notificationId: { type: ['string', 'null'] },
        immediate: { type: 'boolean' },
        replyTo: { type: ['string', 'null'] },
      },
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Recipient.schema());

module.exports = Email;
