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

const TEMPLATE_TYPES = require('../../constant/procedure/template-type.constant').keys;

class TemplateReference {
  constructor(opt) {
    this._id = new ObjectId();
    this.name = '';
    this.types = [];
    this.tenantCode = [];
    this.campusCode = [];
    this.preventClone = false;
    this.preventRemove = false;
    this.preventShare = false;
    this.preventEditTitle = false;
    this.maxExpirationDays = null;
    this.createBySystem = false;

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

  fillObject(opt) {
    this._id = new ObjectId(opt._id);
    this.name = opt.name || '';
    this.types = opt.types || [];
    this.tenantCode = opt.tenantCode || [];
    this.campusCode = opt.campusCode || [];
    this.preventClone = opt.preventClone || false;
    this.preventRemove = opt.preventRemove || false;
    this.preventShare = opt.preventShare || false;
    this.preventEditTitle = opt.preventEditTitle || false;
    this.maxExpirationDays = opt.maxExpirationDays || null;
    this.createBySystem = opt.createBySystem || false;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'template-reference.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        _id: { type: 'object' },
        name: { type: 'string' },
        types: { type: 'array', items: { type: 'string', enum: TEMPLATE_TYPES } },
        tenantCode: { type: 'array', items: { type: 'string' } },
        campusCode: { type: 'array', items: { type: 'string' } },
        preventClone: { type: 'boolean' },
        preventRemove: { type: 'boolean' },
        preventShare: { type: 'boolean' },
        preventEditTitle: { type: 'boolean' },
        maxExpirationDays: { type: ['number', 'null'] },
        createBySystem: { type: 'boolean' },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = TemplateReference;
