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

export default class Controller extends Section {
    constructor($element, $, vnReport) {
        super($element, $);
        this.vnReport = vnReport;
        this.droppableElement = 'a.vn-tr';
    }

    preview(route) {
        this.routeSelected = route;
        this.$.summary.show();
    }

    get checked() {
        const rows = this.$.model.data || [];
        const checkedRows = [];
        for (let row of rows) {
            if (row.checked)
                checkedRows.push(row);
        }

        return checkedRows;
    }

    get totalChecked() {
        return this.checked.length;
    }

    showRouteReport() {
        const routes = [];
        for (let route of this.checked)
            routes.push(route.id);
        const routesId = routes.join(',');

        this.vnReport.show('driver-route', {
            authorization: this.vnToken.token,
            routeId: routesId
        });
    }

    openClonationDialog() {
        this.$.clonationDialog.show();
        this.createdDate = new Date();
    }

    cloneSelectedRoutes() {
        try {
            if (!this.createdDate)
                throw new Error(`The date can't be empty`);

            const routesIds = [];
            for (let route of this.checked)
                routesIds.push(route.id);

            return this.$http.post('Routes/clone', {ids: routesIds, created: this.createdDate}).then(() => {
                this.$.model.refresh();
                this.vnApp.showSuccess(this.$t('Data saved!'));
            });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
        }
    }

    onDrop($event) {
        const target = $event.target;
        const droppable = target.closest(this.droppableElement);
        const ticketId = $event.dataTransfer.getData('Text');
        const routeId = droppable.id;

        if (isNaN(ticketId)) {
            const regexp = new RegExp(/\/ticket\/([0-9]+)\//i);
            const matches = ticketId.match(regexp);

            if (matches && matches.length)
                this.insert(routeId, matches[1]);
            else
                this.vnApp.showError(this.$t('Ticket not found'));
        }

        if (!isNaN(ticketId))
            this.insert(routeId, ticketId);
    }

    insert(routeId, ticketId) {
        routeId = parseInt(routeId);
        ticketId = parseInt(ticketId);

        const query = `Routes/${routeId}/insertTicket`;
        return this.$http.patch(query, {ticketId}).then(() => {
            this.vnApp.showSuccess(this.$t('Data saved!'));
            this.$.model.refresh();
        }).catch(error => {
            if (error.status == 404)
                return this.vnApp.showError(this.$t('Ticket not found'));
            throw error;
        });
    }
}

Controller.$inject = ['$element', '$scope', 'vnReport'];

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