"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
/* eslint-disable class-methods-use-this */
var ObjectId = require('bson').ObjectID;
var clone = require('clone');
var tv4 = require('tv4');
var OCCUPANCY_TYPE = require('../../constant/location/occupancy-type.constant');
var _require = require('../../helper/helper'),
  campusCodeToTenantCode = _require.campusCodeToTenantCode;
var ControlArea = /*#__PURE__*/function () {
  function ControlArea(controlArea) {
    var building = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
      codeYear: 2016,
      fireSuppressionCoverage: false
    };
    _classCallCheck(this, ControlArea);
    this._id = new ObjectId();
    this.name = null;
    this.campusCode = null;
    this.tenantCode = null;
    this.buildingId = null;
    this.rooms = [];
    this.occupancy = 'B';
    this.approvedStorage = [];
    this.fireSuppressionCoverage = null;
    this.isOutdoor = false;
    this.exemption = '';
    this.exemptionNotes = '';
    this.squareFootage = 0;
    this.notify = false;
    if (controlArea) {
      this.fillObject(clone(controlArea), building);
    }
  }
  _createClass(ControlArea, [{
    key: "fillObject",
    value: function fillObject(controlArea, building) {
      this._id = new ObjectId(controlArea._id);
      // eslint-disable-next-line no-underscore-dangle
      this._createdDate = this._id.getTimestamp();
      this.name = controlArea.name || null;
      this.campusCode = controlArea.campusCode;
      this.tenantCode = controlArea.tenantCode || campusCodeToTenantCode(controlArea.campusCode);
      this.buildingId = controlArea.buildingId || building.buildingId;
      this.approvedStorage = controlArea.approvedStorage || [];
      this.isOutdoor = !!controlArea.isOutdoor || false;
      this.exemption = controlArea.exemption || '';
      this.exemptionNotes = controlArea.exemptionNotes || '';
      this.squareFootage = controlArea.squareFootage || 0;
      if (controlArea.fireSuppressionCoverage) {
        this.fireSuppressionCoverage = controlArea.fireSuppressionCoverage;
      }
      var codeYear = building && building.codeYear || 2016;
      var fireSuppressionCoverage = this.getFireSuppresionCoverage(building);
      if (Array.isArray(controlArea.rooms)) {
        this.populateRooms(controlArea, {
          codeYear: codeYear,
          fireSuppressionCoverage: fireSuppressionCoverage
        });
      }
      this.occupancy = this.findLowestOccupancy(codeYear, this.rooms);
      this.maq = this.buildMaq(codeYear);
      if (codeYear === 2001 && this.occupancy !== 'H8') {
        delete this.maq['Combustible Dust'];
      }
      this.notify = building && typeof building.notify === 'boolean' ? building.notify : !!controlArea.notify;
    }
  }, {
    key: "getFireSuppresionCoverage",
    value: function getFireSuppresionCoverage(building) {
      if (typeof this.fireSuppressionCoverage === 'string') {
        return this.fireSuppressionCoverage === 'Yes';
      }
      return building.fireSuppressionCoverage;
    }
  }, {
    key: "buildMaq",
    value: function buildMaq(codeYear) {
      // Standard units for MAQ are lbs(solid), gal(liquid, liquefied gas), cubic feet(gas)
      var maq = {};
      if (codeYear === 2016) {
        maq = {
          'Combustible Liquid: IIIB': {
            solid: null,
            liquid: 13200,
            gas: null
          },
          'Cryogenic Flammable': {
            solid: null,
            liquid: 45,
            gas: null
          },
          'Cryogenic Inert': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Cryogenic Oxidizing': {
            solid: null,
            liquid: 45,
            gas: null
          },
          'Explosive: Division 1-1': {
            solid: 1,
            liquid: 1,
            gas: null
          },
          'Explosive: Division 1-2': {
            solid: 1,
            liquid: 1,
            gas: null
          },
          'Explosive: Division 1-3': {
            solid: 10,
            liquid: 10,
            gas: null
          },
          'Explosive: Division 1-4': {
            solid: 50,
            liquid: 50,
            gas: null
          },
          'Explosive: Division 1-4G': {
            solid: 125,
            liquid: null,
            gas: null
          },
          'Explosive: Division 1-5': {
            solid: 1,
            liquid: 1,
            gas: null
          },
          'Explosive: Division 1-6': {
            solid: 1,
            liquid: null,
            gas: null
          },
          'Flammable Gas': {
            solid: null,
            liquid: null,
            gas: 1000
          },
          'Flammable Gas Liquefied': {
            solid: null,
            liquid: 150,
            gas: null
          },
          'Flammable Liquid: IA': {
            solid: null,
            liquid: 30,
            gas: null
          },
          'Flammable Solid': {
            solid: 125,
            liquid: null,
            gas: null
          },
          'Organic Peroxide: UD': {
            solid: 1,
            liquid: 1,
            gas: null
          },
          'Organic Peroxide: I': {
            solid: 5,
            liquid: 5,
            gas: null
          },
          'Organic Peroxide: II': {
            solid: 50,
            liquid: 50,
            gas: null
          },
          'Organic Peroxide: III': {
            solid: 125,
            liquid: 125,
            gas: null
          },
          'Organic Peroxide: IV': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Organic Peroxide: V': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Oxidizer: 4': {
            solid: 1,
            liquid: 1,
            gas: null
          },
          'Oxidizer: 3': {
            solid: 10,
            liquid: 10,
            gas: null
          },
          'Oxidizer: 2': {
            solid: 250,
            liquid: 250,
            gas: null
          },
          'Oxidizer: 1': {
            solid: 4000,
            liquid: 4000,
            gas: null
          },
          'Oxidizing Gas': {
            solid: null,
            liquid: null,
            gas: 1500
          },
          'Oxidizing Gas Liquefied': {
            solid: null,
            liquid: 150,
            gas: null
          },
          Pyrophoric: {
            solid: 4,
            liquid: 4,
            gas: 50
          },
          'Unstable Reactive: 4': {
            solid: 1,
            liquid: 1,
            gas: 10
          },
          'Unstable Reactive: 3': {
            solid: 5,
            liquid: 5,
            gas: 50
          },
          'Unstable Reactive: 2': {
            solid: 50,
            liquid: 50,
            gas: 750
          },
          'Unstable Reactive: 1': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Water Reactive: 3': {
            solid: 5,
            liquid: 5,
            gas: null
          },
          'Water Reactive: 2': {
            solid: 50,
            liquid: 50,
            gas: null
          },
          'Water Reactive: 1': {
            solid: null,
            liquid: null,
            gas: null
          },
          Corrosive: {
            solid: 5000,
            liquid: 500,
            gas: 810
          },
          'Corrosive Liquefied': {
            solid: null,
            liquid: 150,
            gas: null
          },
          'Highly Toxic': {
            solid: 10,
            liquid: 10,
            gas: 20
          },
          'Highly Toxic Liquefied': {
            solid: null,
            liquid: 4,
            gas: null
          },
          Toxic: {
            solid: 500,
            liquid: 500,
            gas: 810
          },
          'Toxic Liquefied': {
            solid: null,
            liquid: 150,
            gas: null
          }
        };
        if (this.occupancy === 'M' || this.occupancy === 'S') {
          maq['Flammable Liquid: IB, IC & Combustible Liquid: II & Combustible Liquid: IIIA'] = {
            solid: null,
            liquid: 1600,
            gas: null
          };
        } else {
          maq['Combustible Liquid: II'] = {
            solid: null,
            liquid: 120,
            gas: null
          };
          maq['Combustible Liquid: IIIA'] = {
            solid: null,
            liquid: 330,
            gas: null
          };
          maq['Flammable Liquid: IA'] = {
            solid: null,
            liquid: 30,
            gas: null
          };
          maq['Flammable Liquid: IB, IC'] = {
            solid: null,
            liquid: 120,
            gas: null
          };
          maq['Flammable Liquid: IA, IB, IC'] = {
            solid: null,
            liquid: 120,
            gas: null
          };
        }
      } else if (codeYear === 2001) {
        maq = {
          'Combustible Liquid: II': {
            solid: null,
            liquid: 120,
            gas: null
          },
          'Combustible Liquid: IIIA': {
            solid: null,
            liquid: 330,
            gas: null
          },
          'Combustible Liquid: IIIB': {
            solid: null,
            liquid: 13200,
            gas: null
          },
          'Combustible Dust': {
            solid: 1,
            // cubic feet
            liquid: null,
            gas: null
          },
          'Combustible Fiber: Loose': {
            solid: 100,
            // cubic feet
            liquid: 0,
            gas: null
          },
          'Combustible Fiber: Bailed': {
            solid: 1000,
            // cubic feet
            liquid: 0,
            gas: null
          },
          'Cryogenic, Flammable or Oxidizing': {
            solid: null,
            liquid: 45,
            gas: null
          },
          'Explosive Material (CFC2001)': {
            solid: 0,
            liquid: 0,
            gas: null
          },
          'Flammable Solid': {
            solid: 125,
            liquid: null,
            gas: null
          },
          'Flammable Gas': {
            solid: null,
            liquid: null,
            gas: 750
          },
          'Flammable Gas Liquefied': {
            solid: null,
            liquid: 15,
            // gallons
            gas: null
          },
          'Flammable Liquid: IA': {
            solid: null,
            liquid: 30,
            gas: null
          },
          'Flammable Liquid: IB': {
            solid: null,
            liquid: 60,
            // gallons
            gas: null
          },
          'Flammable Liquid: IC': {
            solid: null,
            liquid: 90,
            // gallons
            gas: null
          },
          'Flammable Liquid: IA, IB, IC': {
            solid: null,
            liquid: 120,
            gas: null
          },
          'Organic Peroxide: UD': {
            solid: 0,
            liquid: 0,
            gas: null
          },
          'Organic Peroxide: I': {
            solid: 5,
            liquid: 5,
            gas: null
          },
          'Organic Peroxide: II': {
            solid: 50,
            liquid: 50,
            gas: null
          },
          'Organic Peroxide: III': {
            solid: 125,
            liquid: 125,
            gas: null
          },
          'Organic Peroxide: IV': {
            solid: 500,
            liquid: 500,
            gas: null
          },
          'Organic Peroxide: V': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Oxidizer: 4': {
            solid: 0,
            liquid: 0,
            gas: null
          },
          'Oxidizer: 3': {
            solid: 10,
            liquid: 10,
            gas: null
          },
          'Oxidizer: 2': {
            solid: 250,
            liquid: 250,
            gas: null
          },
          'Oxidizer: 1': {
            solid: 4000,
            liquid: 4000,
            gas: null
          },
          'Oxidizing Gas': {
            solid: null,
            liquid: null,
            gas: 1500
          },
          'Oxidizing Gas Liquefied': {
            solid: null,
            liquid: 15,
            // in gallons
            gas: null
          },
          Pyrophoric: {
            solid: 0,
            liquid: 0,
            gas: 0
          },
          'Unstable Reactive: 4': {
            solid: 0,
            liquid: 0,
            gas: 0
          },
          'Unstable Reactive: 3': {
            solid: 5,
            liquid: 5,
            gas: 50
          },
          'Unstable Reactive: 2': {
            solid: 50,
            liquid: 50,
            gas: 750
          },
          'Unstable Reactive: 1': {
            solid: null,
            liquid: null,
            gas: null
          },
          'Water Reactive: 3': {
            solid: 5,
            liquid: 5,
            gas: null
          },
          'Water Reactive: 2': {
            solid: 50,
            liquid: 50,
            gas: null
          },
          'Water Reactive: 1': {
            solid: null,
            liquid: null,
            gas: null
          },
          Corrosive: {
            solid: 5000,
            liquid: 500,
            gas: 810
          },
          'Highly Toxic': {
            solid: 10,
            liquid: 10,
            gas: 0
          },
          'Irritant (CFC2001)': {
            solid: null,
            liquid: null,
            gas: 810
          },
          'Other Health Hazard Material (CFC2001)': {
            solid: null,
            liquid: null,
            gas: 810
          },
          'Sensitizer (CFC2001)': {
            solid: null,
            liquid: null,
            gas: 810
          },
          Toxic: {
            solid: 500,
            liquid: 500,
            gas: 810
          }
        };
      }
      return maq;
    }
  }, {
    key: "validate",
    value: function validate() {
      return tv4.validateMultiple(this, ControlArea.schema());
    }
  }, {
    key: "findLowestOccupancy",
    value: function findLowestOccupancy(codeYear, rooms) {
      // for 2016 code year: B(A,B E, F, I, R) < L < S&M < H (1-5)
      // for 2001 code year: B < H8
      var occupanyByRank = {};
      OCCUPANCY_TYPE[codeYear].forEach(function (o) {
        occupanyByRank[o.value] = o.sort;
      });
      var type;
      if (!rooms || !rooms.length) {
        type = 'B';
      } else {
        var occupancies = Array.from(new Set(rooms.map(function (r) {
          return r.occupancy;
        })));
        type = occupancies.reduce(function (acc, cur) {
          return !acc || occupanyByRank[cur] < occupanyByRank[acc] ? cur : acc;
        }, null);
      }
      var occupancy = occupanyByRank[type] === 0 ? 'B' : type;
      return occupancy;
    }
  }, {
    key: "populateRooms",
    value: function populateRooms(controlArea, _ref) {
      var _this = this;
      var codeYear = _ref.codeYear,
        fireSuppressionCoverage = _ref.fireSuppressionCoverage;
      var possibleOccupancies = OCCUPANCY_TYPE[codeYear || 2016].filter(function (o) {
        return !(o.value === 'H8' || o.value === 'L') || fireSuppressionCoverage && !_this.isOutdoor;
      }).map(function (o) {
        return o.value;
      });
      controlArea.rooms.forEach(function (r) {
        var room = _objectSpread({}, r);
        if (!possibleOccupancies.some(function (o) {
          return o === room.occupancy;
        })) {
          room.occupancy = 'B';
        }
        _this.rooms.push(room);
      });
    }
  }, {
    key: "classifications",
    value: function classifications(type) {
      switch (type) {
        case 'healthHazards':
          return ['Corrosive', 'Toxic', 'Highly Toxic', 'Corrosive Liquefied', 'Toxic Liquefied', 'Highly Toxic Liquefied'];
        case 'canLiquefied':
          return ['Oxidizing', 'Corrosive', 'Toxic', 'Flammable Gas'];
        default:
          return [];
      }
    }
  }, {
    key: "convertToBand",
    value: function convertToBand(band) {
      var cryogenic = [];
      switch (true) {
        case !!band.match('Liquefied'):
          return [{
            name: band.split(' Liquefied')[0],
            "class": []
          }, {
            name: 'Liquefied Gas',
            "class": []
          }];
        case !!band.match('Cryogenic'):
          cryogenic = [{
            name: 'Cryogenic',
            "class": []
          }];
          if (band.match('Flammable')) {
            cryogenic.push({
              name: 'Flammable Gas',
              "class": []
            });
          } else if (band.match('Oxidizing')) {
            cryogenic.push({
              name: 'Oxidizing Gas',
              "class": []
            });
          } else if (band.match('Inert')) {
            cryogenic[0]["class"].push('Inert');
          }
          return cryogenic;
        case !!band.match('Flammable Liquid'):
          return [{
            name: 'Flammable Liquid',
            "class": band.split(': ')[1].split(',').map(function (i) {
              return i.trim();
            })
          }];
        case !!band.match('Oxidizer'):
          return [{
            name: 'Oxidizers',
            "class": ["Class ".concat(band.split(': ')[1])]
          }];
        case !!band.match(':'):
          return [{
            name: band.split(': ')[0],
            "class": [band.split(': ')[1]]
          }];
        default:
          return [{
            name: band,
            "class": []
          }];
      }
    }
  }], [{
    key: "schema",
    value: function schema() {
      return {
        $schema: 'http://json-schema.org/draft-04/schema#',
        id: 'control-area.schema.json',
        type: 'object',
        additionalProperties: false,
        properties: {
          _id: {
            type: ['object', 'null']
          },
          _createdDate: {
            type: 'object'
          },
          name: {
            type: ['string']
          },
          campusCode: {
            type: ['string']
          },
          tenantCode: {
            type: ['string']
          },
          buildingId: {
            type: ['string']
          },
          rooms: {
            type: 'array',
            item: {
              type: 'object'
            }
          },
          occupancy: {
            type: ['string']
          },
          fireSuppressionCoverage: {
            type: ['null', 'string']
          },
          approvedStorage: {
            type: 'array',
            item: {
              type: 'string'
            }
          },
          isOutdoor: {
            type: 'boolean'
          },
          exemption: {
            type: 'string'
          },
          exemptionNotes: {
            type: 'string'
          },
          squareFootage: {
            type: 'number'
          },
          codeYear: {
            type: 'number'
          },
          maq: {
            type: 'object'
          },
          notify: {
            type: 'boolean'
          }
        },
        required: Object.keys(new ControlArea())
      };
    }
  }]);
  return ControlArea;
}();
module.exports = ControlArea;