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

const Card = require('./card');

class ReferenceCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'REFERENCE';
    this.details = {
      referenceId: null,
      referenceTitle: null,
      referenceType: null,
      referenceLabel: {},
      notes: null,
    };

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

  fillObject(details) {
    this.details.referenceId = details.referenceId ? new ObjectId(details.referenceId) : null;
    this.details.referenceTitle = details.referenceTitle || null;
    this.details.referenceType = details.referenceType || null;
    this.details.referenceLabel = details.referenceLabel || {};
    this.details.notes = details.notes || null;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'reference-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              referenceId: { type: ['object', 'null'] },
              referenceTitle: { type: ['string', 'null'] },
              referenceType: { type: ['string', 'null'] },
              referenceLabel: { type: 'object' },
              notes: { type: ['string', 'null'] },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = ReferenceCard;
