import { Inject, Injectable } from '@angular/core';
import {
    IOnlineBoardUrlDateParams,
    IOnlineBoardRoutePageUrlParams,
} from '@online-board/services/url/types';
import { OnlineBoardUrlBuilderService } from '@online-board/services/url/url-builder.service';
import { IFlightId } from '@typings/flight/flight-id';
import { ONLINE_BOARD_URL_BASE } from '@online-board/services/url/url-base';
import { IOnlineBoardRequestMode } from './types';

@Injectable()
export class OnlineBoardRequestBuilderService {
    private readonly area;

    constructor(
        private urlService: OnlineBoardUrlBuilderService,
        @Inject(ONLINE_BOARD_URL_BASE) public base,
    ) {
        this.area = base;
    }

    buildRouteRequest(params: IOnlineBoardRoutePageUrlParams) {
        if (!params.departure && !params.arrival) {
            return undefined;
        }

        if (!params.departure) {
            return this.buildArrivalRequest(params);
        }

        if (!params.arrival) {
            return this.buildDepartureRequest(params);
        }

        const mode: IOnlineBoardRequestMode = 'route';
        const datePart = this.buildDatePart(params);

        return `${this.area}-${mode}-${params.departure}-${params.arrival}-${datePart}`;
    }

    buildFlightNumberRequest(flightId: IFlightId, searchDate: Date) {
        const mode: IOnlineBoardRequestMode = 'flight';
        const flightNumber = this.urlService.formatFlightId(flightId, false);
        const datePart = this.buildDatePart({ date: searchDate });

        return `${this.area}-${mode}-${flightNumber}-${datePart}`;
    }

    private buildArrivalRequest(params: IOnlineBoardRoutePageUrlParams) {
        const mode: IOnlineBoardRequestMode = 'arrival';
        const datePart = this.buildDatePart(params);

        return `${this.area}-${mode}-${params.arrival}-${datePart}`;
    }

    private buildDepartureRequest(params: IOnlineBoardRoutePageUrlParams) {
        const mode: IOnlineBoardRequestMode = 'departure';
        const datePart = this.buildDatePart(params);

        return `${this.area}-${mode}-${params.departure}-${datePart}`;
    }

    private buildDatePart(params: IOnlineBoardUrlDateParams) {
        const urlDate = this.urlService.formatDate(params.date);
        const timeRange = this.urlService.formatTimeRange({
            timeFrom: params.timeFrom,
            timeTo: params.timeTo,
        });

        return timeRange ? `${urlDate}-${timeRange}` : urlDate;
    }
}
