import ngModule from '../module';
import Section from 'salix/components/section';

export default class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.canChangePassword = false;
        this.canEnableCheckBox = true;
    }

    $onChanges() {
        if (this.client) {
            this.account = this.client.account;
            this.isCustomer();
            this.checkConditions();
        }
    }

    isCustomer() {
        if (this.client.id) {
            this.$http.get(`Clients/${this.client.id}/hasCustomerRole`).then(res => {
                this.canChangePassword = res.data && res.data;
            });
        }
    }

    checkConditions() {
        if (this.client.id) {
            this.$http.get(`Clients/${this.client.id}/isValidClient`).then(res => {
                this.canEnableCheckBox = res.data;
            });
        }
    }

    onPassOpen() {
        this.newPassword = '';
        this.repeatPassword = '';
        this.$.$apply();
    }

    onPassChange() {
        try {
            if (!this.newPassword)
                throw new Error(`You must enter a new password`);
            if (this.newPassword != this.repeatPassword)
                throw new Error(`Passwords don't match`);
            const data = {
                newPassword: this.newPassword
            };

            this.$http.patch(`Clients/${this.client.id}/setPassword`, data).then(() => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
            });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));

            return false;
        }

        return true;
    }

    onSubmit() {
        const data = {
            name: this.account.name,
            email: this.account.email,
            active: this.account.active
        };
        this.$http.patch(`Clients/${this.client.id}/updateUser`, data).then(() => {
            this.$.watcher.notifySaved();
            this.$.watcher.updateOriginalData();
        });
    }
}
Controller.$inject = ['$element', '$scope'];

ngModule.vnComponent('vnClientWebAccess', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        client: '<'
    }
});