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

class Sublocation {
  constructor(opt) {
    this._id = null;
    this.inventoryId = null;
    this.buildingId = null;
    this.buildingName = '';
    this.floorId = null;
    this.floorName = '';
    this.roomId = null;
    this.roomNumber = null;
    this.name = null;
    this.barcode = null;
    this.temperature = null;
    this.pressure = null;
    this.isPrivate = false;
    this.hazardCodes = [];
    this.pictogramCodes = [];

    if (opt) {
      this.fillObject(opt);
    }
  }

  fillObject(opt) {
    this._id = new ObjectId(opt._id);
    this.inventoryId = ObjectId.isValid(opt.inventoryId) ? new ObjectId(opt.inventoryId) : null;
    this.buildingId = opt.buildingId;
    this.buildingName = opt.buildingName || '';
    this.floorId = opt.floorId;
    this.floorName = opt.floorName || '';
    this.roomId = opt.roomId;
    this.roomNumber = opt.roomNumber;
    this.name = opt.name || null;
    this.barcode = opt.barcode || '';
    this.temperature = opt.temperature || null;
    this.pressure = opt.pressure || null;
    this.isPrivate = opt.isPrivate || false;

    if (opt.hazardCodes) {
      opt.hazardCodes.forEach((code) => this.hazardCodes.push(code));
    }

    if (opt.pictogramCodes) {
      opt.pictogramCodes.forEach((code) => this.pictogramCodes.push(code));
    }
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'sublocation.schema.json',
      type: 'object',
      properties: {
        _id: { type: 'object' },
        inventoryId: { type: 'object' },
        buildingId: { type: 'string' },
        buildingName: { type: 'string' },
        floorId: { type: 'string' },
        floorName: { type: 'string' },
        roomId: { type: 'string' },
        roomNumber: { type: 'string' },
        name: { type: 'string' },
        barcode: { type: ['string', null] },
        temperature: { type: 'string' },
        pressure: { type: 'string' },
        isPrivate: { type: 'boolean' },
        hazardCodes: { type: 'array', item: { type: 'string' } },
        pictogramCodes: { type: 'array', item: { type: 'string' } },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = Sublocation;
