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

/**
 * Mixin that encapsulates some of the route authentication behavior.
 *
 * If the user is logged into an app, but has no app roles, this will redirect them to index.
 * This is as opposed to the default ember-simple-auth logic which only checks logged in, not roles
 *
 * Usage: (in a routes file)
 * ```javascript
 * import Route from '@ember/routing/route';
 * import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
 * import AuthCheckMixin from '@bennerinformatics/ember-fw-gc/mixins/auth-check';
 * import AuthRouteMixin from '@bennerinformatics/ember-fw-gc/mixins/auth-route';
 *
 * export default Route.extend(AuthenticatedRouteMixin, AuthCheckMixin, AuthRouteMixin, {
 *     // your code here
 * });
 * ```
 * This mixin is used by the [AuthRoute](AuthRoute.html) in your app, which means that any route which extends `AuthRoute` in the
 * Informatics Apps incorporates this mixin.
 *
 * @public
 * @class AuthRouteMixin
 * @extends Ember.Mixin
 * @module Mixins
 */
export default Mixin.create({
    currentUser: injectService(),
    session: injectService(),

    /**
     * Route to transition to if the check (for authentication and having roles) fails. This should ordinarily be left to the default, but could be overwritten if the need arose.
     *
     * @public
     * @property rejectedRoute
     * @type {String}
     * @default index
     */
    rejectedRoute: 'index',

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

        if (this.get('session.isAuthenticated') && !this.get('currentUser.hasRoles')) {
            return this.transitionTo(this.get('rejectedRoute'));
        }

        return superResult;
    }
});