import { Injectable } from '@angular/core';
import { IScheduleRouteParams } from '@schedule/services/url/types';
import { ScheduleUrlParserService } from '@schedule/services/url/url-parser.service';

@Injectable()
export class ScheduleRequestParserService {
    constructor(private urlParser: ScheduleUrlParserService) {}

    parseRouteRequest(request: string): IScheduleRouteParams {
        // request string contains area === 'schedule', mode === 'route',
        // route params and maybe return route params.
        // First to params are always 'schedule' and 'route' so we can
        // skip them.
        const [, , ...paramsArray] = request.split('-');
        const outboundParams = [];

        let index = 0;

        for (; index < 4; index++) {
            // copy outbound departure(0), arrival(1), dateFrom(2) and dateTo(3)
            outboundParams[index] = paramsArray[index];
        }

        while (!/[a-zA-Z]{3}/.test(paramsArray[index])) {
            // copy outbound time range and connections if there are.
            outboundParams[index] = paramsArray[index];
            index++;
        }

        const inboundParams = paramsArray.slice(index);

        return {
            outbound: this.urlParser.parseRouteParams(outboundParams.join('-')),
            inbound: inboundParams.length
                ? this.urlParser.parseRouteParams(inboundParams.join('-'))
                : undefined,
        };
    }
}
