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

class Controller {
    constructor($http, $scope, $stateParams) {
        this.$http = $http;
        this.$scope = $scope;
        this.$stateParams = $stateParams;
        this.filter = {
            include: {
                observations: 'observationType'
            },
            order: ['isActive DESC', 'nickname ASC']
        };
    }

    get client() {
        return this._client;
    }

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

    get addresses() {
        return this._addresses;
    }

    set addresses(value) {
        this._addresses = value;
        this.sortAddresses();
    }

    setDefault(address) {
        let query = `/client/api/Clients/${this.$stateParams.id}`;
        let params = {defaultAddressFk: address.id};
        this.$http.patch(query, params).then(res => {
            if (res.data) {
                this.client.defaultAddressFk = res.data.defaultAddressFk;
                this.sortAddresses();
            }
        });
    }

    isDefaultAddress(address) {
        if (!this.client) return;
        return this.client.defaultAddressFk === address.id;
    }

    /**
     * Sort address by default address
     */
    sortAddresses() {
        if (!this.client || !this.addresses) return;
        this.$scope.model.data = this.addresses.sort((a, b) => {
            return this.isDefaultAddress(b) - this.isDefaultAddress(a);
        });
    }
}
Controller.$inject = ['$http', '$scope', '$stateParams'];

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