import { Pipe, PipeTransform } from '@angular/core';
import {
    compareByArrivalAsc,
    compareByArrivalDesc,
    compareByDepartureAsc,
    compareByDepartureDesc,
    compareByDurationAsc,
    compareByDurationDesc,
    FlightModel,
    ListItem,
    ScheduleSortMode,
} from '../models-legacy';

@Pipe({
    name: 'sortFlightsBy',
})
export class SortFlightsByPipe implements PipeTransform {
    // cannot use generic for some reason, thats why going ListItem instead of FlightModel
    transform(flights: ListItem<FlightModel>[], sortBy: ScheduleSortMode): ListItem<FlightModel>[] {
        const compareFn = getFlightsCompareFunction(sortBy);
        return flights.slice().sort(compareFn);
    }
}

function getFlightsCompareFunction(sortBy: ScheduleSortMode) {
    switch (sortBy) {
        case ScheduleSortMode.departureUp:
            return compareByDepartureAsc;
        case ScheduleSortMode.departureDown:
            return compareByDepartureDesc;
        case ScheduleSortMode.timeUp:
            return compareByDurationAsc;
        case ScheduleSortMode.timeDown:
            return compareByDurationDesc;
        case ScheduleSortMode.arrivalUp:
            return compareByArrivalAsc;
        case ScheduleSortMode.arrivalDown:
            return compareByArrivalDesc;
    }
}

export function sortFlights(flights: FlightModel[], sortBy: ScheduleSortMode) {
    const compareFn = getFlightsCompareFunction(sortBy);
    return flights.sort(compareFn);
}
