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

/**
 * Mixing to handle common index route logic.
 * Allows redirecting the user to a specified route, conditionally upon them having no roles.
 * The purpose is to allow for an error page to display if the user has no permissions within the
 * current app.
 *
 * Usage: (in a routes file)
 * ```javascript
 * import Route from '@ember/routing/route';
 * import IndexMixin from '@bennerinformatics/ember-fw-gc/mixins/index-route';
 *
 * export default Route.extend(IndexMixin, {
 *      mainRoute: 'main'
 *     // your code here
 * });
 * ```
 * This should be incorporated into every app's `route/index.js`. In practice, this means that the main page of your
 * app should be called something other than `index`, so that index can be used properly for displaying the no
 * permissions page.
 *
 * @public
 * @class MixinIndexRoute
 * @extends Ember.Mixin
 * @module Mixins
 */
export default Mixin.create({
    currentUser: inject(),
    session: inject(),

    /**
     * Route to transition to if the condition succeeds. This should be set in every index route.
     *
     * @public
     * @property mainRoute
     * @type {String}
     */
    mainRoute: null,

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

        if (this.get('session.isAuthenticated')) {
            let redirect = this.get('mainRoute');
            // either the roles muse not be required, or we must have a role
            if (this.get('currentUser.hasRoles') && !isEmpty(redirect)) {
                return this.transitionTo(redirect);
            }
        }

        return superResult;
    }
});