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

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

class TemplateSection {
  constructor(opt) {
    this.id = null;
    this.header = '';
    this.allowableCards = [];
    this.cardDefinitions = [];
    this.isMovable = true;

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

  fillObject(opt) {
    this.id = new ObjectId(opt.id);
    this.header = opt.header || '';
    this.allowableCards = opt.allowableCards || [];
    this.isMovable = !!opt.isMovable;

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

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

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

module.exports = TemplateSection;
