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

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

class EquipmentCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'EQUIPMENT';
    this.details = {
      name: null,
      assetNumber: '',
      barcode: '',
      geoLocation: null,
      location: null,
      contactPerson: null,
      contactPhone: null,
      notes: null,
    };

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

  fillObject(details) {
    this.details.name = details.name || null;
    this.details.assetNumber = details.assetNumber || null;
    this.details.barcode = details.barcode || null;
    this.details.geoLocation = details.geoLocation || null;
    this.details.location = details.location || null;
    this.details.contactPerson = details.contactPerson || null;
    this.details.contactPhone = details.contactPhone || null;
    this.details.notes = details.notes || null;
    this.isValid = !!(this.details.assetNumber || this.details.barcode || this.details.name);
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'equipment-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              name: { type: 'string' },
              assetNumber: { type: ['string', 'null'] },
              barcode: { type: ['string', 'null'] },
              geoLocation: { type: ['object', 'null'] },
              location: { type: ['object', 'null'] },
              contactPerson: { type: ['object', 'null'] },
              contactPhone: { type: ['string', 'null'] },
              notes: { type: ['string', 'null'] },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = EquipmentCard;
