import ngModule from '../../module';

export default class Controller {
    constructor($scope, $state) {
        this.$ = $scope;
        this.$state = $state;
        this.$stateParams = $state.params;
    }

    removeObservation(index) {
        this.$.watcher.setDirty();
        this.$.model.remove(index);
    }

    cancel() {
        this.goToIndex();
    }

    goToIndex() {
        this.$state.go('client.card.address.index');
    }

    get postcodeSelection() {
        return this._postcodeSelection;
    }

    set postcodeSelection(selection) {
        const hasValue = this._postcodeSelection;
        this._postcodeSelection = selection;

        if (!selection || !hasValue) return;

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

        this.address.city = town.name;
        this.address.provinceFk = province.id;
        this.address.countryFk = country.id;
    }

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

    onSubmit() {
        this.$.watcher.check();
        this.$.watcher.realSubmit()
            .then(() => this.$.model.save(true))
            .then(() => {
                this.$.watcher.setPristine();
                this.$.watcher.notifySaved();
                this.card.reload();
                this.goToIndex();
            });
    }
}
Controller.$inject = ['$scope', '$state'];

ngModule.component('vnClientAddressEdit', {
    template: require('./index.html'),
    controller: Controller,
    require: {
        card: '^vnClientCard'
    }
});