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

class Controller extends Section {
    open() {
        this.$.SMSDialog.show();
    }

    charactersRemaining() {
        const element = this.$.message;
        const value = element.input.value;

        const maxLength = 160;
        const textAreaLength = new Blob([value]).size;
        return maxLength - textAreaLength;
    }

    onResponse() {
        try {
            if (!this.sms.destination)
                throw new Error(`The destination can't be empty`);
            if (!this.sms.message)
                throw new Error(`The message can't be empty`);
            if (this.charactersRemaining() < 0)
                throw new Error(`The message it's too long`);

            this.$http.post(`Clients/${this.$params.id}/sendSms`, this.sms).then(res => {
                this.vnApp.showMessage(this.$t('SMS sent!'));

                if (res.data) this.emit('send', {response: res.data});
            });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
            return false;
        }
        return true;
    }
}

Controller.$inject = ['$element', '$scope', '$http', '$translate', 'vnApp'];

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