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

const Card = require('./card');
const CardLabelValue = require('./card-label-value');

class SelectCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'SELECT';
    this.details = {
      name: null,
      optionsId: null,
      questions: [],
    };

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

  fillObject(details) {
    this.details.name = details.name || null;
    this.details.optionsId = details.optionsId ? new ObjectId(details.optionsId) : null;
    this.details.questions = details.questions ? details.questions.map((opt) => new CardLabelValue(opt)) : [];
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'select-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              name: { type: 'string' },
              optionsId: { type: 'object' },
              questions: { type: 'array', items: { $ref: 'card-label-value.schema.json' } },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());
tv4.addSchema(CardLabelValue.schema());

module.exports = SelectCard;
