const tv4 = require('tv4');
const ROLES = require('../../constant/core/roles.constant');

class Role {
  constructor(opt) {
    this.role = null;
    this.campusCode = null;
    this.tenantCode = null;
    this.groupIds = [];
    this.types = [];

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

  fillObject(opt) {
    this.role = opt.role || null;
    this.campusCode = opt.campusCode || null;
    this.tenantCode = opt.tenantCode || null;
    this.groupIds = opt.groupIds || [];

    if (opt.groupId && !this.groupIds.includes(opt.groupId)) {
      // eslint-disable-next-line no-console
      console.warn('Warning!! groupId from Role object has been deprecated, use groupIds as an array of string');
      this.groupIds.push(opt.groupId);
    }

    this.types = opt.types ? opt.types : [];
  }

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

  static schema() {
    const roleEnums = Object.keys(ROLES).map((role) => ROLES[role]);
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'role.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        role: { enum: roleEnums },
        campusCode: { type: ['string', 'null'] },
        tenantCode: { type: ['string', 'null'] },
        groupIds: { type: 'array', item: { type: 'string' } },
        groupName: { type: ['string', 'null'] },
        types: { type: 'array', item: { type: 'string' } },
      },
      required: Object.keys(this),
    };
  }
}

module.exports = Role;
