import Ember from 'ember';

import OsfTokenLoginControllerMixin from 'ember-osf/mixins/osf-token-login-controller';

import {
    getAuthUrl
} from 'ember-osf/utils/auth';

export default Ember.Controller.extend(OsfTokenLoginControllerMixin, {
    toast: Ember.inject.service(),
    authUrl: getAuthUrl(),
    actions: {
        loginSuccess() {
            this.transitionToRoute('index');
        },
        loginFail(/* err */) {
            this.get('toast').error('Login failed');
        }
    }
});
      The session service.
      @property session
      @readOnly
      @type SessionService
      @public
    */
    session: Ember.inject.service('session'),
    routing: Ember.inject.service('-routing'),

    /**
      Checks whether the session is authenticated, and if it is not, redirects to the login URL. (Sending back to this page after a successful transition)

      __If `beforeModel` is overridden in a route that uses this mixin, the route's
     implementation must call `this._super(...arguments)`__ so that the mixin's
     `beforeModel` method is actually executed.
      @method beforeModel
      @public
    */
    beforeModel(transition) {
        if (!this.get('session.isAuthenticated')) {
            // Reference: http://stackoverflow.com/a/39054607/414097
            let routing = this.get('routing');
            let params = Object.values(transition.params).filter(param => Object.values(param).length);
            let url = routing.generateURL(transition.targetName, params, transition.queryParams);
            window.location = getAuthUrl(url);
        } else {
            return this._super(...arguments);
        }
    }
});