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

class Controller extends Section {
    set invoceInIntrastat(value) {
        this._invoceInIntrastat = value;

        if (value) this.calculateTotals();
    }

    get invoceInIntrastat() {
        return this._invoceInIntrastat;
    }

    calculateTotals() {
        this.amountTotal = 0.0;
        this.netTotal = 0.0;
        this.stemsTotal = 0.0;
        if (!this.invoceInIntrastat) return;

        this.invoceInIntrastat.forEach(intrastat => {
            this.amountTotal += intrastat.amount;
            this.netTotal += intrastat.net;
            this.stemsTotal += intrastat.stems;
        });
    }

    add() {
        this.$.model.insert({});
    }

    deleteIntrastat($index) {
        this.$.model.remove($index);
        this.$.model.save().then(() => {
            this.vnApp.showSuccess(this.$t('Data saved!'));
            this.calculateTotals();
        });
    }

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

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