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

export default class Controller extends Section {
    get client() {
        return this._client;
    }

    set client(value) {
        this._client = value;

        if (!value) return;

        if (!value.bankEntityFk)
            this.autofillBic();
    }

    onSubmit() {
        let shouldNotify = false;

        if (this.hasPaymethodChanges())
            shouldNotify = true;

        this.$.watcher.submit().then(() => {
            if (shouldNotify)
                this.vnApp.showMessage(this.$t('Notification sent!'));
        });
    }

    hasPaymethodChanges() {
        let orgData = this.$.watcher.orgData;

        let payMethod = orgData.payMethodFk != this.client.payMethodFk;
        let iban = orgData.iban != this.client.iban;
        let dueDay = orgData.dueDay != this.client.dueDay;

        return payMethod || iban || dueDay;
    }

    onAccept(data) {
        this.client.bankEntityFk = data.id;
    }

    get ibanCountry() {
        if (!this.client || !this.client.iban) return false;

        let countryCode = this.client.iban.substr(0, 2);

        return countryCode;
    }

    autofillBic() {
        if (!this.client || !this.client.iban) return;

        let bankEntityId = parseInt(this.client.iban.substr(4, 4));
        let filter = {where: {id: bankEntityId}};

        if (this.ibanCountry != 'ES') return;

        this.$http.get(`BankEntities`, {filter}).then(response => {
            const hasData = response.data && response.data[0];

            if (hasData)
                this.client.bankEntityFk = response.data[0].id;
            else if (!hasData)
                this.client.bankEntityFk = null;
        });
    }
}

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