import {inject as service} from '@ember/service';
import {alias} from '@ember/object/computed';
import BaseModal from '@bennerinformatics/ember-fw/components/modals/base';

import {isBadRequestError} from 'ember-ajax/errors';
import {validator, buildValidations} from 'ember-cp-validations';
import ValidationMixin from '@bennerinformatics/ember-fw/mixins/validation';

import layout from '@bennerinformatics/ember-fw-gc/templates/components/modals/change-password';

const ChangePasswordValidation = buildValidations({
    currentPass: [
        validator('presence', {
            presence: true,
            message: 'You must supply a current password.'
        }),
        validator('password', {
            dependentKeys: ['wrongPassword']
        })
    ],
    newPass: validator('presence', {
        presence: true,
        allowBlank: true,
        message: 'You must supply a new password.'
    }),
    confirmPass: validator('confirmation', {
        on: 'newPass',
        message: 'Passwords do not match.'
    })
});

/**
 * A modal which allows you to change your current password. It has three textfields: Current Password, New Password, and Confirm Password. It will invalidate if current password is not
 * passed in or if it is the wrong password, or if new password and confirm password do not match. This modal is called from the FwHeader component (if they have a GC generated
 * password, they will be forced to select a "secure" password) and the Profile page. There is no configuration needed for this modal, and you do not need to call it, since it is handled by
 * components within Ember FW GC.
 *
 * @class ChangePasswordModal
 * @module Components
 */
export default BaseModal.extend(ChangePasswordValidation, ValidationMixin, {
    layout,
    currentPass: '',
    newPass: '',
    confirmPass: '',

    wrongPassword: false,

    config: service(),
    ajax: service(),
    notifications: service(),

    needSecure: alias('model.needSecure'),
    ignoreCurrent: alias('model.ignoreCurrent'),

    actions: {
        confirm() {
            let validate = (this.get('ignoreCurrent')) ? this.validate({excludes: ['currentPass']}) : this.validate();

            return validate.then(() => {
                let data = this.getProperties('currentPass', 'newPass', 'confirmPass');

                if (this.get('model.userId')) {
                    data.userId = this.get('model.userId');
                }

                let usersUrl = this.get('config').formGCUrl('users', 'changePassword');
                this.set('wrongPassword', false);

                return this.get('ajax').put(usersUrl, {data});
            });
        },

        success() {
            this.set('currentPass', '');
            this.set('newPass', '');
            this.set('confirmPass', '');
            this.clearValidations();

            this.get('notifications').showSuccess('Password changed successfully!', 'profile', true);

            this.send('closeModal');
        },

        error(error) {
            if (isBadRequestError(error)) {
                this.set('wrongPassword', true);
            }
        }
    }
});