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

/**
 * A mixin designed to be used by routes that wish to check if the user
 * is still logged in before transitioning to a new route.
 *
 * Usage: (in a routes/*.js file)
 * ```javascript
 * import Ember from 'ember';
 * import AuthCheckMixin from '@bennerinformatics/ember-fw-gc/mixin/auth-check';
 *
 * export default Ember.Route.extend(AuthCheckMixin, {
 *     // route 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.
 *
 * @public
 * @class AuthCheckMixin
 * @extends Ember.Mixin
 * @module Mixins
 */
export default Mixin.create({
    currentUser: injectService(),
    session: injectService(),

    actions: {
        willTransition(transition) {
            return this.get('currentUser').check().then((isActive) => {
                if (!isActive) {
                    transition.abort();
                    this.get('session').triggerReAuthenticate(transition);
                } else {
                    return this._super(...arguments);
                }
            });
        }
    }
});