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

const Card = require('./card');
const CardOptionValue = require('./card-option-value');

class CheckboxCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'CHECKBOX';
    this.details = {
      name: null,
      countLabel: null,
      count: null,
      hideNotes: false,
      notes: null,
      optionsId: null,
      selectedOptions: [],
    };

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

  fillObject(details) {
    this.details.name = details.name || null;
    this.details.countLabel = details.countLabel || null;
    this.details.hideNotes = 'hideNotes' in details ? details.hideNotes : false;
    this.details.optionsId = details.optionsId ? new ObjectId(details.optionsId) : null;
    this.details.selectedOptions = details.selectedOptions
      ? details.selectedOptions.map((opt) => new CardOptionValue(opt))
      : [];
    this.details.notes = details.notes || null;
    this.details.count = details.countLabel
      ? this.details.selectedOptions.reduce((acc, curr) => acc + curr.count, 0)
      : null;
    this.isValid = !!this.details.selectedOptions.length;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'checkbox-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              name: { type: 'string' },
              countLabel: { type: ['string', 'null'] },
              count: { type: ['number', 'null'] },
              hideNotes: { type: 'boolean' },
              optionsId: { type: 'object' },
              selectedOptions: { type: 'array', items: { $ref: 'card-option-value.schema.json' } },
              notes: { type: ['string', 'null'] },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

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

module.exports = CheckboxCard;
