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

class QuestionCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'QUESTION';
    this.details = {
      questionType: 'input',
      label: '',
      value: '',
      required: false,
      options: [],
    };

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

  fillObject(details) {
    this.details.label = details.label || this.details.label;
    this.details.questionType = details.questionType || this.details.questionType;
    this.details.value = details.value || this.details.value;
    this.details.required = details.required || this.details.required;
    this.details.options = details.options || this.details.options;
    this.isValid = !!this.details.value;
  }

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

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

tv4.addSchema(Card.schema());

module.exports = QuestionCard;
