const tv4 = require('tv4');

const { NODE } = require('../../constant/relationship/label.constant');

class Access {
  constructor(opt) {
    this.id = null;
    this.displayName = null;
    this.tenantCode = null;
    this.campusCode = null;
    this.permission = null;
    this.type = null;

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

  fillObject(opt) {
    this.id = opt.id || '';
    this.displayName = opt.displayName || '';
    this.tenantCode = opt.tenantCode || null;
    this.campusCode = opt.campusCode || null;
    this.permission = opt.permission || '';
    this.type = opt.type || '';
    if (opt.user) {
      this.id = opt.user.id || opt.user.userId;
    }
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'access.schema.json',
      type: 'object',
      properties: {
        id: { type: 'string' },
        displayName: { type: 'string' },
        tenantCode: { type: 'string' },
        campusCode: { type: ['string', 'null'] },
        permission: {
          enum: [
            'ACKNOWLEDGE',
            'AMEND',
            'COMMENT',
            'CONTACT',
            'DELETE',
            'EDIT',
            'MEMBER',
            'OWNER',
            'READ',
            'REVIEW',
            'SUBMIT',
            'WRITE',
          ],
        },
        type: { enum: ['SYSTEM', ...Object.values(NODE)] },
      },
      required: Object.keys(this),
    };
  }

  static fromPerson(user, permission) {
    return new Access({
      id: user.userId,
      displayName: `${user.firstName} ${user.lastName}`,
      tenantCode: user.tenantCode,
      campusCode: user.campusCode,
      permission,
      type: 'PERSON',
    });
  }
}

module.exports = Access;
