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();
    }

    showTicketPopup(route) {
        this.routeSelected = route;
        this.$.ticketPopup.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 routesIds = [];
        for (let route of this.checked)
            routesIds.push(route.id);
        const stringRoutesIds = routesIds.join(',');

        if (this.checked.length <= 1) {
            const url = `api/Routes/${stringRoutesIds}/driver-route-pdf?access_token=${this.vnToken.token}`;
            window.open(url, '_blank');
        } else {
            const serializedParams = this.$httpParamSerializer({
                access_token: this.vnToken.token,
                id: stringRoutesIds
            });
            const url = `api/Routes/downloadZip?${serializedParams}`;
            window.open(url, '_blank');
        }
    }

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

    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;
        });
    }

    updateAttributes(route) {
        if (route.started == null || route.finished == null)
            return this.vnApp.showError(this.$t('You must select a valid time'));
        if (route.created == null)
            return this.vnApp.showError(this.$t('You must select a valid date'));
        const params = {
            workerFk: route.workerFk,
            agencyModeFk: route.agencyModeFk,
            vehicleFk: route.vehicleFk,
            created: route.created,
            description: route.description,
            started: route.started,
            finished: route.finished
        };
        const query = `Routes/${route.id}/`;
        this.$http.patch(query, params).then(res => {
            this.vnApp.showSuccess(this.$t('Data saved!'));
        });
    }

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

        const params = {isOk: true};
        for (let routeId of routes)
            this.$http.patch(`Routes/${routeId}`, params);
    }
}

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

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