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

const Card = require('./card');
const Family = require('../chemical/family');

class ChemicalCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'CHEMICAL';
    this.details = {
      family: null,
      amount: {
        value: null,
        units: null,
        required: false,
        visible: false,
      },
    };

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

  fillObject(details) {
    this.details.family = details.family ? new Family(details.family) : null;
    if (details.amount && typeof details.amount === 'object') {
      this.details.amount.value = details.amount.value;
      this.details.amount.units = details.amount.units;
      this.details.amount.required = !!details.amount.required;
      this.details.amount.visible = !!details.amount.visible;
    }
    this.isValid = !!(
      this.details.family &&
      (!this.details.amount.required || (this.details.amount.value && this.details.amount.units))
    );
  }

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

  getLabel() {
    return this.details.family ? [this.details.family._id] : [];
  }

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'chemical-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              family: { type: 'object', item: { $ref: 'family.schema.json' } },
              amount: {
                type: 'object',
                properties: {
                  amount: 'number',
                  units: 'string',
                  required: 'boolean',
                  visible: 'boolean',
                },
              },
            },
          },
        },
      ],
      required: Object.keys(new ChemicalCard()),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = ChemicalCard;
