const tv4 = require('tv4');
const clone = require('clone');

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

class ValueUnitCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'VALUE_UNIT';
    this.details = {
      count: null,
      countLabel: null,
      info: null,
      infoDescription: null,
      value: null,
      valueDescription: null,
      units: null,
      unitOptions: [],
    };

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

  fillObject(details) {
    this.details.count = details.count || details.value || null;
    this.details.countLabel = details.countLabel || null;
    this.details.info = details.info || null;
    this.details.infoDescription = details.infoDescription || null;
    this.details.value = details.value || null;
    this.details.valueDescription = details.valueDescription || null;
    this.details.units = details.units || null;
    this.details.unitOptions = details.unitOptions || [];
    this.isValid = !!this.details.value;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'text-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              count: { type: ['number', 'null'] },
              countLabel: { type: ['string', 'null'] },
              info: { type: ['string', 'null'] },
              infoDescription: { type: ['string', 'null'] },
              value: { type: 'string' },
              valueDescription: { type: 'string' },
              units: { type: 'string' },
              unitOptions: { type: 'array', item: { type: 'string' } },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = ValueUnitCard;
