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

export default class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.client = {
            active: true
        };
    }

    onSubmit() {
        return this.$.watcher.submit().then(json => {
            this.$state.go('client.card.basicData', {id: json.data.id});
        });
    }

    get province() {
        return this._province;
    }

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

        if (!selection) return;

        const country = selection.country;

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

    get town() {
        return this._town;
    }

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

        if (!selection) return;

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

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

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

        if (postcodes.length === 1)
            this.client.postcode = postcodes[0].code;
    }

    get postcode() {
        return this._postcode;
    }

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

        if (!selection) return;

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

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

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

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

    onResponse(response) {
        this.client.postcode = response.code;
        this.client.city = response.city;
        this.client.provinceFk = response.provinceFk;
        this.client.countryFk = response.countryFk;
    }
}

Controller.$inject = ['$element', '$scope'];

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