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

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.include = {
            relation: 'bankEntity',
            scope: {
                fields: ['countryFk', 'id', 'name', 'bic']
            }
        };
    }

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

    onResponse(response) {
        const data = this.$.model.data;
        const supplierAccount = data[this.currentRowIndex];
        supplierAccount.bankEntityFk = response.id;
    }

    showBankEntity(event, $index) {
        if (event.defaultPrevented) return;
        event.preventDefault();
        this.currentRowIndex = $index;
        this.$.bankEntity.open();
    }

    onBankEntityAccept() {
        const query = `SupplierAccounts/${this.$params.id}/createBankEntity`;
        return this.$http.patch(query, this.newBankEntity)
            .then(res => this.supplierAccount.bankEntityFk = res.data.id);
    }

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

ngModule.vnComponent('vnSupplierAccount', {
    template: require('./index.html'),
    controller: Controller,
    require: {
        card: '^vnSupplierCard'
    }
});