import { IConnectingFlight } from './contracts';
import { ConnectingFlight } from './flight.model';
import { IFlightStrategy } from './flight.strategy';
import { RouteTypeLegacy } from '../enumerators';
import { createFlights } from './populate.logic';

export class ConnectingFlightStrategy implements IFlightStrategy {
    constructor(private getStrategy: (type: RouteTypeLegacy) => IFlightStrategy) {}

    getLegs(flight: ConnectingFlight) {
        return flight.flights
            .map((f) => this.getStrategy(f.routeType).getLegs(f))
            .reduce((allLegs, flightLegs) => allLegs.concat(flightLegs), []);
    }
    getFlights(flight: ConnectingFlight) {
        return [...flight.flights];
    }

    getFirstLeg(flight: ConnectingFlight) {
        const first = this.getFirstFlight(flight);
        return this.getStrategy(first.routeType).getFirstLeg(first);
    }
    getCurrentLeg(flight: ConnectingFlight) {
        const legs = this.getLegs(flight);
        return legs.find((l) => l.isCurrent) ?? legs[0];
    }
    getLastLeg(flight: ConnectingFlight) {
        const last = this.getLastFlight(flight);
        return this.getStrategy(last.routeType).getLastLeg(last);
    }

    getFirstFlight(flight: ConnectingFlight) {
        return flight.flights[0];
    }
    getLastFlight(flight: ConnectingFlight) {
        return flight.flights[flight.flights.length - 1];
    }

    getFlightId(flight: ConnectingFlight, isLast: boolean) {
        const { flights } = flight;

        const single = isLast ? flights[flights.length - 1] : flights[0];

        return this.getStrategy(single.routeType).getFlightId(single);
    }

    fromContract(contract: IConnectingFlight) {
        const flights = createFlights(contract.flights);

        const flight: Partial<ConnectingFlight> = {
            ...contract,
            isMultiFlight: true,
            isMultiLeg: true,
            flights,
        };

        return flight;
    }
}
