import ngModule from '../module';
import Descriptor from 'salix/components/descriptor';
import UserError from 'core/lib/user-error';
class Controller extends Descriptor {
    constructor($element, $, $rootScope) {
        super($element, $);
        this.$rootScope = $rootScope;
    }

    get worker() {
        return this.entity;
    }

    set worker(value) {
        this.entity = value;
        if (value)
            this.getIsExcluded();

        if (this.entity && !this.entity.user.emailVerified)
            this.getPassRequirements();
    }

    getIsExcluded() {
        this.$http.get(`WorkerDisableExcludeds/${this.entity.id}/exists`).then(data => {
            this.workerExcluded = data.data.exists;
        });
    }

    handleExcluded() {
        if (this.workerExcluded)
            this.$http.delete(`WorkerDisableExcludeds/${this.entity.id}`);
        else
            this.$http.post(`WorkerDisableExcludeds`, {workerFk: this.entity.id, dated: new Date});

        this.workerExcluded = !this.workerExcluded;
    }

    loadData() {
        return this.getData('Workers/descriptor', {filter: {where: {id: this.id}}})
            .then(res => this.entity = res.data[0]);
    }

    getPassRequirements() {
        this.$http.get('UserPasswords/findOne')
            .then(res => {
                this.passRequirements = res.data;
            });
    }

    setPassword() {
        if (!this.newPassword)
            throw new UserError(`You must enter a new password`);
        if (this.newPassword != this.repeatPassword)
            throw new UserError(`Passwords don't match`);
        this.$http.patch(
            `Workers/${this.entity.id}/setPassword`, {newPass: this.newPassword}
        ) .then(() => {
            this.vnApp.showSuccess(this.$translate.instant('Password changed!'));
        }).then(() => this.loadData());
    }
}

Controller.$inject = ['$element', '$scope', '$rootScope', 'vnConfig'];

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