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

class Controller extends Section {
    $onInit() {
        this.refresh();
    }

    get path() {
        return `Zones/${this.$params.id}/warehouses`;
    }

    refresh() {
        let filter = {include: 'warehouse'};
        this.$http.get(this.path, {params: {filter}})
            .then(res => this.$.data = res.data);
    }

    onCreate() {
        this.selected = {};
        this.$.dialog.show();
    }

    onSave() {
        this.$http.post(this.path, this.selected)
            .then(() => {
                this.selected = null;
                this.isNew = null;
                this.$.dialog.hide();
                this.refresh();
            });

        return false;
    }

    onDelete(row) {
        this.$.confirm.show();
        this.deleteRow = row;
    }

    delete() {
        let row = this.deleteRow;
        if (!row) return;
        return this.$http.delete(`${this.path}/${row.id}`)
            .then(() => {
                let index = this.$.data.indexOf(row);
                if (index !== -1) this.$.data.splice(index, 1);
                this.deleteRow = null;
            });
    }
}

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