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

class Controller extends Section {
    $postLink() {
        this.onSearch();
    }

    onSearch(params) {
        this.$.model.applyFilter({}, params).then(() => {
            const data = this.$.model.data;
            this.$.treeview.data = data;
        });
    }

    onFetch(item) {
        const params = item ? {parentId: item.id} : null;
        return this.$.model.applyFilter({}, params)
            .then(() => this.$.model.data);
    }

    onSort(a, b) {
        if (b.selected !== a.selected) {
            if (a.selected == null)
                return 1;
            if (b.selected == null)
                return -1;
            return b.selected - a.selected;
        }

        return a.name.localeCompare(b.name);
    }

    exprBuilder(param, value) {
        switch (param) {
        case 'search':
            return {name: {like: `%${value}%`}};
        }
    }

    onSelection(value, item) {
        if (value == null)
            value = undefined;
        const params = {geoId: item.id, isIncluded: value};
        const path = `zones/${this.zone.id}/toggleIsIncluded`;
        this.$http.post(path, params);
    }
}

ngModule.vnComponent('vnZoneLocation', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        zone: '<'
    },
    require: {
        card: '^vnZoneCard'
    }
});