const ObjectId = require('bson').ObjectID;
const clone = require('clone');
const tv4 = require('tv4');

const { createCardFactory } = require('../../helper/card-factory');

class DocumentSection {
  constructor(opt) {
    this.id = null;
    this.header = null;
    this.allowableCards = [];
    this.cards = [];
    this.isMovable = true;

    if (opt) {
      this.fillObject(clone(opt));
    }
  }

  fillObject(opt) {
    this.id = new ObjectId(opt.id);
    this.header = opt.header || null;
    this.isMovable = typeof opt.isMovable === 'boolean' ? opt.isMovable : this.isMovable;
    this.allowableCards = opt.allowableCards || [];

    if (opt.cards) {
      opt.cards.forEach((card) => {
        this.cards.push(createCardFactory(card.type, card));
      });
    }
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'document-section.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        id: { type: ['object', 'null'] },
        header: { type: 'string' },
        isMovable: { type: 'boolean' },
        allowableCards: { type: 'array', item: { type: 'object' } },
        cards: { type: 'array', items: { type: 'object' } },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = DocumentSection;
