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

const FacilityBuilding = require('./facility-building');

class Facility {
  constructor(opt) {
    this._id = null;
    this.name = null;
    this.campusCode = null;
    this.tenantCode = null;
    this.buildings = [];
    this.cersId = null;
    this.epaId = null;
    this.hazardousLiquidLimit = {
      value: 55,
      unit: 'gal',
    };
    this.hazardousSolidLimit = {
      value: 500,
      unit: 'lb',
    };
    this.compressedGasLimit = {
      value: 200,
      unit: 'ft3',
    };
    this.liquefiedCarbonDioxideLimit = {
      value: 200,
      unit: 'lbs',
    };

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

  fillObject(opt) {
    Object.keys(this).forEach((prop) => {
      if (this[prop]) {
        Object.assign(this[prop], opt[prop]);
      } else {
        this[prop] = opt[prop] || null;
      }
    });

    this._id = new ObjectId(opt._id);
    // eslint-disable-next-line no-underscore-dangle
    this._createdDate = this._id.getTimestamp();
    this.buildings = Array.isArray(opt.buildings)
      ? opt.buildings.map((building) => new FacilityBuilding(building))
      : [];
  }

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

  static schema() {
    const facility = new Facility();
    const requiredFacility = Object.keys(facility);

    const valueUnitSchema = {
      type: 'object',
      properties: {
        value: { type: 'number' },
        unit: { type: 'string' },
      },
      required: ['value', 'unit'],
    };

    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'facility.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        _id: { type: 'object' },
        _createdDate: { type: 'object' },
        name: { type: 'string' },
        campusCode: { type: 'string' },
        tenantCode: { type: 'string' },
        buildings: { type: 'array', item: { $ref: 'facility-building.schema.json' } },
        cersId: { type: ['string', 'null'] },
        epaId: { type: ['string', 'null'] },
        hazardousLiquidLimit: valueUnitSchema,
        hazardousSolidLimit: valueUnitSchema,
        compressedGasLimit: valueUnitSchema,
        liquefiedCarbonDioxideLimit: valueUnitSchema,
      },
      required: requiredFacility,
    };
  }
}

tv4.addSchema(FacilityBuilding.schema());

module.exports = Facility;
