"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetroShapePointsFixer = void 0;
const GeoMeasurementHelper_1 = require("../../../../../../helpers/geo/GeoMeasurementHelper");
const ModuleContainerToken_1 = require("../../../../../ioc/ModuleContainerToken");
const VPContainerToken_1 = require("../../../../ioc/VPContainerToken");
const MetroRouteHelper_1 = require("../../../runs/helpers/MetroRouteHelper");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const CachedMetroRailtrackLookup_1 = require("../../data-access/metro/CachedMetroRailtrackLookup");
let MetroShapePointsFixer = class MetroShapePointsFixer {
    constructor(cachedMetroRailTrackLookup, geoMeasurementHelper) {
        this.cachedMetroRailTrackLookup = cachedMetroRailTrackLookup;
        this.geoMeasurementHelper = geoMeasurementHelper;
    }
    async fix(data) {
        try {
            const clonedData = structuredClone(data);
            // load metro obvody
            const metroRailtrackLookup = await this.cachedMetroRailTrackLookup.getAllByRouteName(MetroRouteHelper_1.MetroRouteHelper.getRouteName(data.trip_id));
            let lastKnownStopSequence = null;
            const maxStopSequence = clonedData.stop_times.length;
            for (let index = 0; index < clonedData.shapes_anchor_points.length; index++) {
                const shape = clonedData.shapes_anchor_points[index];
                const possibleStops = this.getPossibleStops(clonedData.stop_times, lastKnownStopSequence);
                const closestMetroRailtrack = this.getClosestMetroRailtrack(shape, metroRailtrackLookup, possibleStops);
                const thisStopSequence = this.getSequenceByStopId(closestMetroRailtrack.gtfs_stop_id, clonedData.stop_times);
                if (thisStopSequence) {
                    lastKnownStopSequence = thisStopSequence;
                }
                shape.at_stop = closestMetroRailtrack.gtfs_stop_id && thisStopSequence ? true : false;
                shape.this_stop_sequence = thisStopSequence;
                shape.next_stop_sequence = lastKnownStopSequence ? Math.min(lastKnownStopSequence + 1, maxStopSequence) : 2;
                shape.last_stop_sequence = lastKnownStopSequence && lastKnownStopSequence > 1 ? lastKnownStopSequence : 1;
                if (shape.at_stop) {
                    shape.last_stop_sequence = shape.this_stop_sequence;
                }
            }
            return clonedData;
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("Unable to fix metro shape points: " + err.message, this.constructor.name, err);
        }
    }
    getSequenceByStopId(gtfs_stop_id, stop_times) {
        const regex = /U(?<node>.*)Z/;
        const node = regex.exec(gtfs_stop_id || "")?.groups?.node;
        if (node && node.length > 0) {
            return stop_times.find((stop_time) => regex.exec(stop_time.stop_id)?.groups?.node === node)?.stop_sequence || null;
        }
        else {
            return null;
        }
    }
    getClosestMetroRailtrack(shape, metroRailtrackLookup, possibleStops) {
        // find closest metroRailtrack for shape.coordinates
        const result = metroRailtrackLookup
            .map((metroRailtrack) => {
            return {
                ...metroRailtrack,
                distance: this.geoMeasurementHelper.getDistanceInMeters(shape.coordinates, metroRailtrack.coordinates.coordinates),
            };
        })
            .sort((a, b) => a.distance - b.distance);
        const resultsWithing15Meters = result.filter((el) => el.distance < 15);
        if (resultsWithing15Meters.length > 0) {
            for (const railtrack of resultsWithing15Meters) {
                if (possibleStops.some((el) => el === railtrack.gtfs_stop_id)) {
                    return railtrack;
                }
            }
            return resultsWithing15Meters[0];
        }
        // if no railtrack is within 15 meters, return closest railtrack without stop_id
        return result.filter((el) => !el.gtfs_stop_id)[0];
    }
    getPossibleStops(stopTimes, lastKnownStopSequence) {
        // since we dont know direction for railtrack data, we check concrete stops in one direction
        // to ensure proper matching with shape
        const result = [];
        if (lastKnownStopSequence === null) {
            result.push(stopTimes[0].stop_id);
        }
        else {
            result.push(stopTimes[lastKnownStopSequence - 1].stop_id);
            if (lastKnownStopSequence < stopTimes.length) {
                result.push(stopTimes[lastKnownStopSequence].stop_id);
            }
        }
        return result;
    }
};
exports.MetroShapePointsFixer = MetroShapePointsFixer;
exports.MetroShapePointsFixer = MetroShapePointsFixer = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.CachedMetroRailTrackLookup)),
    __param(1, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.GeoMeasurementHelper)),
    __metadata("design:paramtypes", [CachedMetroRailtrackLookup_1.CachedMetroRailTrackLookup,
        GeoMeasurementHelper_1.GeoMeasurementHelper])
], MetroShapePointsFixer);
//# sourceMappingURL=MetroShapePointsFixer.js.map