import ngModule from '../module';
import Dialog from 'core/components/dialog';
import './style.scss';

class Controller extends Dialog {
    constructor($element, $, $transclude) {
        super($element, $, $transclude);
    }

    getSelectedTickets(tickets) {
        const selectedTickets = [];

        if (tickets) {
            for (let i = 0; i < tickets.length; i++) {
                if (tickets[i].checked)
                    selectedTickets.push(tickets[i]);
            }
        }
        return selectedTickets;
    }

    updateVolume() {
        let url = `Routes/${this.route.id}/updateVolume`;
        this.$http.post(url).then(() => {
            this.$.model.refresh();
            if (this.parentReload)
                this.parentReload();
        });
    }

    setTicketsRoute() {
        const tickets = this.getSelectedTickets(this.possibleTickets);
        if (tickets.length === 0) return;

        const updates = [];

        for (let ticket of tickets) {
            delete ticket.checked;
            const update = {
                where: {id: ticket.id},
                data: {routeFk: this.route.id}
            };

            updates.push(update);
        }

        const data = {creates: [], updates: updates, deletes: []};
        return this.$http.post(`Tickets/crud`, data)
            .then(() => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
                this.updateVolume();
                this.hide();
            });
    }

    unlinkZone(ticket) {
        const params = {
            agencyModeId: this.route.agencyModeFk,
            zoneId: ticket.zoneFk,
        };

        const query = `Routes/unlink`;
        this.$http.post(query, params).then(() => {
            this.vnApp.showSuccess(this.$t('Data saved!'));
            this.$.model.refresh();
            this.hide();
        });
    }
}
Controller.$inject = ['$element', '$scope', '$transclude'];

ngModule.vnComponent('vnRouteTicketPopup', {
    slotTemplate: require('./index.html'),
    controller: Controller,
    bindings: {
        route: '<',
        model: '<?',
        parentReload: '&'
    }
});