import Controller from '@ember/controller';
import {inject as injectService} from '@ember/service';
import {alias} from '@ember/object/computed';
import {reject} from 'rsvp';
/**
 * The Profile Page is a page which is designed for a user, who does not have access to Group Control to change aspects about their Group Control user.
 * It allows you to change `nameFirst`, `namePref`, `nameLast`, and `email` for the currently authenticated user. It is able to be accessed through the
 * `FwGcNav` component by clicking the name in the right and then clicking "profile" in the dropdown that appears.
 *
 * Everything is set up for you, from the route to the controller to the template to even the link to click in the dropdown to call it.
 * There is nothing you need to do to configure this (so long as you already imported the router as instructed in the setup instructions for
 * [Ember FW GC](https://linformatics.bitbucket.io/docs/addons/client/ember-fw-gc/setup)).
 *
 * @class ProfilePage
 * @module Pages
 */
export default Controller.extend({
    currentUser: injectService(),
    config: injectService(),
    ajax: injectService(),
    notifications: injectService(),

    user: alias('model.user'),
    settings: alias('model.settings'),

    actions: {
        saveUser() {
            let userModel = this.get('user');
            let data = userModel.getProperties('nameFirst', 'nameLast', 'namePref', 'email');
            let userUrl = this.get('config').formGCUrl('users', this.get('currentUser.userId'));

            return userModel.validate().then(() => {
                return this.get('ajax').put(userUrl, {
                    data: {user: data}
                }).then(({user}) => {
                    delete user.id;

                    this.get('notifications').showSuccess('Profile Saved', 'profile', true);

                    this.get('currentUser').setProperties(user);
                    userModel.get('hasValidated').clear();
                }).catch((e) => {
                    this.get('notifications').showError('An error occurred', 'profile', true);

                    return reject(e);
                });
            });
        },

        saveSettings() {
            let settings = this.get('settings');
            let settingsUrl = this.get('config').formGCUrl('settings', {app: this.get('config.appId')});

            return this.get('ajax').put(settingsUrl, {
                data: {settings}
            }).then(() => {
                this.get('notifications').showSuccess('Settings Saved', 'settings', true);
            }).catch((e) => {
                this.get('notifications').showError('An error occurred', 'settings', true);

                return reject(e);
            });
        },

        changePassword() {
            this.get('currentUser').changePassword();
        }
    }
});