import ngModule from '../module';
import Section from 'salix/components/section';
import UserError from 'core/lib/user-error';

class Controller extends Section {
    constructor($element, $, vnWeekDays) {
        super($element, $);
        this.expense = {};
    }
    taxRate(invoiceInTax, taxRateSelection) {
        const taxTypeSage = taxRateSelection && taxRateSelection.rate;
        const taxableBase = invoiceInTax && invoiceInTax.taxableBase;

        if (taxTypeSage && taxableBase)
            return (taxTypeSage / 100) * taxableBase;

        return 0;
    }

    add() {
        this.$.model.insert({
            invoiceIn: this.$params.id
        });
    }

    onSubmit() {
        this.$.watcher.check();
        this.$.model.save().then(() => {
            this.$.watcher.notifySaved();
            this.$.watcher.updateOriginalData();
            this.card.reload();
        });
    }

    onResponse() {
        try {
            if (!this.expense.code)
                throw new Error(`The code can't be empty`);
            if (!this.expense.description)
                throw new UserError(`The description can't be empty`);

            const data = [{
                id: this.expense.code,
                isWithheld: this.expense.isWithheld,
                name: this.expense.description
            }];

            this.$http.post(`Expenses`, data) .then(() => {
                this.vnApp.showSuccess(this.$t('Expense saved!'));
            });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
        }
    }
}

ngModule.vnComponent('vnInvoiceInTax', {
    template: require('./index.html'),
    controller: Controller,
    require: {
        card: '^vnInvoiceInCard'
    },
    bindings: {
        invoiceIn: '<'
    }
});