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

export default class Controller extends Section {
    get province() {
        return this._province;
    }

    // Province auto complete
    set province(selection) {
        const oldValue = this._province;
        this._province = selection;

        if (!selection || !oldValue) return;

        const country = selection.country;

        if (!this.supplier.countryFk)
            this.supplier.countryFk = country.id;
    }

    get town() {
        return this._town;
    }

    // Town auto complete
    set town(selection) {
        const oldValue = this._town;
        this._town = selection;

        if (!selection || !oldValue) return;

        const province = selection.province;
        const country = province.country;
        const postcodes = selection.postcodes;

        if (!this.supplier.provinceFk)
            this.supplier.provinceFk = province.id;

        if (!this.supplier.countryFk)
            this.supplier.countryFk = country.id;

        if (!this.supplier.postCode && postcodes.length === 1)
            this.supplier.postCode = postcodes[0].code;
    }

    get postcode() {
        return this._postcode;
    }

    // Postcode auto complete
    set postcode(selection) {
        const oldValue = this._postcode;
        this._postcode = selection;

        if (!selection || !oldValue) return;

        const town = selection.town;
        const province = town.province;
        const country = province.country;

        if (!this.supplier.city)
            this.supplier.city = town.name;

        if (!this.supplier.provinceFk)
            this.supplier.provinceFk = province.id;

        if (!this.supplier.countryFk)
            this.supplier.countryFk = country.id;
    }

    onResponse(response) {
        this.supplier.postCode = response.code;
        this.supplier.city = response.city;
        this.supplier.provinceFk = response.provinceFk;
        this.supplier.countryFk = response.countryFk;
    }
}

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