import Mixin from '@ember/object/mixin';
import {isEmpty} from '@ember/utils';
import {inject as injectService} from '@ember/service';

/**
 * Creates a basic `permit` function that will check
 * a user's roles against a list of provided roles using the
 * match function. Designed to be used by a route.
 *
 * Usage: (in a route file)
 * ```javascript
 * import Ember from 'ember';
 * import PermissionsMixin from '@bennerinformatics/ember-fw-gc/mixin/permissions';
 *
 * export default Ember.Route.extend(PermissionsMixin, {
 *     // your code here
 * });
 * ```
 *
 * This mixin is used by the addon AuthRoute, which is extended by both [AuthRoute](AuthRoute.html) and [RestrictedRoute](RestrictedRoute.html), so then, this mixin
 * is incorporated behind the scenes into all the routes used in the Informatics Apps (whether `AuthRoute` or `RestrictedRoute`).
 *
 * @public
 * @class PermissionsMixin
 * @extends Ember.Mixin
 * @module Mixins
 */

export default Mixin.create({
    currentUser: injectService(),

    /**
     * Checks a role or list of roles against a user's available roles.
     * If the check fails, the app will transition to the route specified.
     *
     * @public
     * @method permit
     * @param  {String|Array} roles Roles to check
     * @param  {String} goTo  Route to transition to if the check fails
     * @return {Ember.Transition|null}
     */
    permit(roles, goTo) {
        let user = this.get('currentUser');

        goTo = goTo || 'index';

        if (isEmpty(roles) || !user.match(roles)) {
            // TODO: notifications
            return this.transitionTo(goTo);
        }
    }
});