import ngModule from '../module';

export default class Controller {
    constructor($scope, $http, $state) {
        this.$scope = $scope;
        this.$http = $http;
        this.$state = $state;
        this.filter = {
            include: [
                {relation: 'agencyMode', fields: ['name']},
                {relation: 'warehouse', fields: ['name']}
            ]
        };
    }

    exprBuilder(param, value) {
        switch (param) {
        case 'search':
            return /^\d+$/.test(value)
                ? {id: value}
                : {name: {like: `%${value}%`}};
        case 'warehouseFk':
        case 'agencyModeFk':
            return {[param]: value};
        }
    }

    /**
     * Clones a zone and all its properties
     * @param {Object} event - Event object
     * @param {Object} zone - Selected item
     */
    clone(event, zone) {
        this.stopEvent(event);
        this.selectedZone = zone;
        this.$scope.clone.show();
    }

    /**
     * Clone response callback
     * @param {String} response - Response string (['ACCEPT', 'CANCEL'])
     */
    onCloneAccept(response) {
        if (!(response == 'ACCEPT' && this.selectedZone)) return;
        const query = `/agency/api/Zones/${this.selectedZone.id}/clone`;
        this.$http.post(query).then(res => {
            if (res && res.data)
                this.$state.go('zone.card.basicData', {id: res.data.id});
        });

        this.selectedZone = null;
    }

    /**
     * Opens a summary modal
     * @param {Object} event - Event object
     * @param {Object} zone - Selected item
     */
    preview(event, zone) {
        this.stopEvent(event);
        this.selectedZone = zone;
        this.$scope.summary.show();
    }

    /**
     * Prevents normal event propagation
     * @param {Object} event - Event object
     */
    stopEvent(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
    }
}

Controller.$inject = ['$scope', '$http', '$state'];

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