import { Injectable } from '@angular/core';
import { IParsedFlightId } from '@typings/flight/flight-id';
import * as moment from 'moment';
import { IUrlTimeRange } from '@typings/common/url';

@Injectable({
    providedIn: 'root',
})
export class UrlParserService {
    parseDate(date: string) {
        let parsed = moment(date, 'YYYYMMDD', true);

        if (parsed.isValid()) {
            return parsed.toDate();
        }

        return undefined;
    }

    parseFlightId(flightId: string): IParsedFlightId {
        const [flightInfo, urlDate] = flightId.split('-');

        const carrier = flightInfo.slice(0, 2) + (flightInfo.length > 2 && flightInfo[2] > '9' ? flightInfo.slice(2,3) : "");
        const suffix = flightInfo.length > 0 && flightInfo.slice(-1)[0] > '9' ? flightInfo.slice(-1) : "";
        const number = flightInfo.slice(carrier.length, flightInfo.length-suffix.length);
        
        return {
            flightNumber: number,
            carrier,
            date: this.parseDate(urlDate),
            suffix: suffix,
        };
    }

    parseTimeRange(timeRange?: string): IUrlTimeRange {
        return {
            timeFrom: timeRange?.slice(0, 4),
            timeTo: timeRange?.slice(4),
        };
    }
}
