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

const UNITS = require('../../constant/chemical/units.constant');

class Product {
  constructor(opt) {
    this.productNumber = null;
    this.quantity = 1;
    this.size = null;
    this.unit = null;

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

  fillObject(opt) {
    this.productNumber = opt.productNumber || null;
    this.quantity = opt.quantity || 1;
    this.size = opt.size || null;
    this.unit = opt.unit || null;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'product.schema.json',
      type: 'object',
      properties: {
        productNumber: { type: 'string' },
        quantity: { type: 'number' },
        size: { type: ['number', 'null'] },
        unit: { anyOf: [{ enum: UNITS.map((unit) => unit.value) }, 'null'] },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = Product;
