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

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

class LocationCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'LOCATION';
    this.details = {
      suiteId: null,
      locations: [],
    };

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

  fillObject(details) {
    this.details.suiteId = details.suiteId ? new ObjectId(details.suiteId) : null;
    this.details.locations = details.locations.map((loc) => ({
      buildingId: loc.buildingId || '',
      floorId: loc.floorId || '',
      roomId: loc.roomId || '',
      buildingName: loc.buildingName || '',
      floorName: loc.floorName || '',
      roomNumber: loc.roomNumber || '',
    }));
    this.isValid = !!this.details.locations.length;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'location-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              suiteId: { type: ['object', 'null'] },
              locations: {
                type: 'array',
                items: {
                  buildingId: { type: ['string', 'null'] },
                  floorId: { type: ['string', 'null'] },
                  roomId: { type: ['string', 'null'] },
                  buildingName: { type: ['string', 'null'] },
                  floorName: { type: ['string', 'null'] },
                  roomNumber: { type: ['string', 'null'] },
                },
              },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = LocationCard;
