import ngModule from '../module';
import Descriptor from 'salix/components/descriptor';

class Controller extends Descriptor {
    get zone() {
        return this.entity;
    }

    set zone(value) {
        this.entity = value;
    }

    onDelete() {
        const $t = this.$translate.instant;
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const filter = {where: {zoneFk: this.id, shipped: {gte: today}}};
        this.$http.get(`Tickets`, {filter}).then(res => {
            const ticketsAmount = res.data.length;
            if (ticketsAmount) {
                const params = {ticketsAmount};
                const question = $t('This zone contains tickets', params, null, null, 'sanitizeParameters');
                this.$.deleteZone.question = question;
                this.$.deleteZone.show();
            } else
                this.deleteZone();
        });
    }

    deleteZone() {
        return this.$http.post(`Zones/${this.id}/deleteZone`).then(() => {
            this.$state.go('zone.index');
            this.vnApp.showSuccess(this.$t('Zone deleted'));
        });
    }

    onCloneAccept() {
        return this.$http.post(`Zones/${this.id}/clone`).
            then(res => this.$state.go('zone.card.basicData', {id: res.data.id}));
    }
}

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