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

const Card = require('./card');
const InventoryHazardSignReference = require('./inventory-hazard-sign-reference');

class InventoryCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'INVENTORY';
    this.isEditable = false;
    this.details = {
      locations: [],
      inventories: [],
      hazardCodes: [],
    };

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

  fillObject(details) {
    this.details.locations = details.locations || null;
    this.details.inventories = details.inventories
      ? details.inventories.map((inv) => new InventoryHazardSignReference(inv))
      : [];
    this.details.hazardCodes = details.hazardCodes || [];
    this.isValid = !!this.details.inventories.length;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'inventory-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              locations: { type: 'array', item: { type: 'object' } },
              inventories: { type: 'array', item: { $ref: 'inventory-hazard-sign-reference.schema.json' } },
              hazardCodes: { type: 'array', item: { type: 'string' } },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = InventoryCard;
