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

export default class Controller extends Section {
    onSubmit() {
        this.$.watcher.submit()
            .then(() => this.$state.go('supplier.card.address.index'));
    }

    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 postcodes = selection.postcodes;

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

        if (!this.address.postalCode && postcodes.length === 1)
            this.address.postalCode = 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;

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

        if (!this.address.provinceFk)
            this.address.provinceFk = province.id;
    }

    onResponse(response) {
        this.address.postalCode = response.code;
        this.address.city = response.city;
        this.address.provinceFk = response.provinceFk;
    }
}

ngModule.vnComponent('vnSupplierAddressEdit', {
    template: require('./index.html'),
    controller: Controller
});