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

/**
 * Mixin that encapsulates some of the route restriction behavior.
 *
 * If a roles array and a rejectedRoute property are specified, this mixin
 * will ensure the user has adequate permissions before proceeding to the route.

 * Mixin designed to be used by a route. Routes that use this mixin **MUST**
 * also use the PermissionsMixin
 *
 * Usage: (in a routes file)
 * ```javascript
 * import Ember from 'ember';
 * import PermissionsMixin from '@bennerinformatics/ember-fw-gc/mixins/permissions';
 * import RestrictedRouteMixin from '@bennerinformatics/ember-fw-gc/mixins/restricted-route';
 *
 * export default Ember.Route.extend(PermissionsMixin, RestrictedRouteMixin, {
 *     // your code here
 * });
 * ```
 *
 * This mixin is used by the [RestrictedRoute](RestrictedRoute.html) in your app, which means that any route which extends `RestrictedRoute` in the
 * Informatics Apps automatically incorporates this mixin.
 *
 * @public
 * @class RestrictedRouteMixin
 * @extends Ember.Mixin
 * @module Mixins
 */
export default Mixin.create({
    /**
     * Array of roles to be passed to the match function
     *
     * @public
     * @property roles
     * @type {Array}
     */
    roles: [],

    /**
     * Route to transition to if the roles check fails. This may have more use case to override than in AuthRoute.
     *
     * @public
     * @property rejectedRoute
     * @type {String}
     * @default index
     */
    rejectedRoute: 'index',

    session: injectService(),

    beforeModel(transition) {
        let superResult = this._super(transition);

        if (this.get('session.isAuthenticated')) {
            this.permit(this.get('roles'), this.get('rejectedRoute'));
        }

        return superResult;
    }
});