import { Injectable } from '@angular/core';
import { IAirportInfo } from '@typings/airport-info';
import { Leg } from '../models-legacy';

type IWithAirportInfo = {
    scheduled: IAirportInfo;
    latest?: IAirportInfo;
};

@Injectable({
    providedIn: 'root',
})
export class OldAirportVisibilityService {
    departureStationForTerminalChange(leg: Leg) {
        return this.shouldShowOldDepartureAirport(leg)
            ? leg.departure
            : undefined;
    }

    arrivalStationForTerminalChange(leg: Leg) {
        return this.shouldShowOldArrivalAirport(leg) ? leg.arrival : undefined;
    }

    private shouldShowOldDepartureAirport(leg: Leg) {
        const { previous } = leg;
        if (!previous) {
            return false;
        }

        if (!this.stationsMatch(previous, leg)) {
            return false;
        }

        return this.shouldReturnStationForTerminalChange(leg.departure);
    }

    private shouldShowOldArrivalAirport(leg: Leg) {
        const { next } = leg;
        if (!next) {
            return false;
        }

        if (!this.stationsMatch(leg, next)) {
            return false;
        }

        return this.shouldReturnStationForTerminalChange(leg.arrival);
    }

    private stationsMatch(firstLeg: Leg, secondLeg: Leg) {
        const latestMatch =
            firstLeg.arrival.latest?.airportCode ===
            secondLeg.departure.latest?.airportCode;
        const scheduledMatch =
            firstLeg.arrival.scheduled.airportCode ===
            secondLeg.departure.scheduled.airportCode;

        return latestMatch && scheduledMatch;
    }

    private shouldReturnStationForTerminalChange(info: IWithAirportInfo) {
        const latestAirport = info.latest?.airportCode;
        const scheduledAirport = info.scheduled.airportCode;

        if (!latestAirport) {
            return false;
        }

        return latestAirport !== scheduledAirport;
    }
}
