import { APP_BASE_HREF, DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { RouteTypeLegacy } from '@shared/enumerators';
import { ViewType } from '@shared/enumerators/flight-request-type.enum';
import { FlightModel } from '@shared/models-legacy';
import { ApiFormatterService } from '@shared/services/api/formatter.service';
import { UrlBuilderService } from '@shared/services/url/url-builder.service';
import { WINDOW } from '.';

@Injectable({
    providedIn: 'root',
})
export class RouterHandlerService {
    constructor(
        @Inject(DOCUMENT) private document: Document,
        private router: Router,
        @Inject(WINDOW) private window$: Window,
        @Inject(APP_BASE_HREF) private baseHref: string,
        private apiFormatter: ApiFormatterService,
        private urlBuilder: UrlBuilderService,
    ) {}

    navigateByUrl(url: string) {
        this.router.navigateByUrl(url);
    }

    toBoard() {
        this.navigateByUrl('/onlineboard');
    }

    toSchedule() {
        this.navigateByUrl('/schedule');
    }

    toBoardDetailsWithBlank(flight: FlightModel) {
        const url = this.getBoardDetailsAbsoluteUrl(flight);
        this.window$.open(url, '_blank');
    }

    getDeparture(flight: FlightModel) {
        if (flight.routeType == RouteTypeLegacy.Direct) {
            return flight.leg.departure.scheduled.airportCode;
        }
        return flight.legs[0].departure.scheduled.airportCode;
    }

    getArrival(flight: FlightModel) {
        if (flight.routeType == RouteTypeLegacy.Direct) {
            return flight.leg.arrival.scheduled.airportCode;
        }
        return flight.legs[flight.legs.length-1].arrival.scheduled.airportCode;
    }

    getDetailsUrl(flight: FlightModel, viewType: ViewType) {
        if (flight.routeType === RouteTypeLegacy.Connecting) {
            if (viewType === ViewType.Onlineboard) {
                return 'onlineboard/' + flight.flights
                    .map((flight) => {
                        return this.formatDetailsUrl(flight, null);
                    })
                    .join('/');
            }
            var url = 'schedule/';
            var prevAirport = '';
            flight.flights.forEach((fl) => {
                var departure = this.getDeparture(fl);
                if (prevAirport != departure) {
                    url += departure+'/';
                }
                var arrival = this.getArrival(fl);
                url += this.formatDetailsUrl(fl, null) + '/' + arrival + '/';
                prevAirport = arrival;
            });
            return url;
        }

        if (viewType === ViewType.Schedule) {
            return 'schedule/' + this.getDeparture(flight)+ '/' + this.formatDetailsUrl(flight, null) + '/' + this.getArrival(flight)+'/';
        }

        return this.formatDetailsUrl(flight, viewType);
    }

    getBoardDetailsUrl(flight: FlightModel) {
        return this.getDetailsUrl(flight, ViewType.Onlineboard);
    }

    getDetailsAbsoluteUrl(flight: FlightModel, viewType: ViewType) {
        const url = this.getDetailsUrl(flight, viewType);
        if (viewType === ViewType.Onlineboard) {
            return this.getAbsoluteUrl(url);
        }

        // TIPDEVII-547 no longer add request, now we share url without it and will not show menu based on request
        return this.getAbsoluteUrl(url);
        // in schedule we have to add 'request' parameter on list or details page
        //if (this.document.location.search.length > 0) {
        //    return this.getAbsoluteUrl(url) + this.document.location.search;
        //} else {
        //    const request = this.document.location.pathname.split('/').slice(2).join('-');
        //    return this.getAbsoluteUrl(url) + "?request=" + request;
        //}
    }

    getBoardDetailsAbsoluteUrl(flight: FlightModel) {
        return this.getDetailsAbsoluteUrl(flight, ViewType.Onlineboard);
    }

    getScheduleDetailsAbsoluteUrl(flight: FlightModel) {
        return this.getDetailsAbsoluteUrl(flight, ViewType.Schedule);
    }

    getAbsoluteUrl(url: string) {
        url = this.router.serializeUrl(this.router.createUrlTree([url]));
        return `${this.document.location.origin}${this.baseHref}${url}`;
    }

    private formatDetailsUrl(flight: FlightModel, viewType: ViewType) {
        const flightInfo = `${flight.flightId.carrier}${flight.flightId.flightNumber}${flight.flightId.suffix}`;
        const date = this.urlBuilder.formatDate(flight.dateToSearchBy);
        if (viewType===null) {
            return `${flightInfo}-${date}`;
        }

        const area =
            viewType === ViewType.Onlineboard ? 'onlineboard' : 'schedule';

        return `${area}/${flightInfo}-${date}`;
    }
}
