import { getFirstLeg, getLastLeg, getTotalMinutes, IFlightTime, Leg } from '.';
import { FlightModel } from './flight.model';

type CompareDirection = 1 | -1;

// all covered with tests as a part of test for sort-flights-by.pipe.spec.ts
export function compareByArrivalDesc(a: FlightModel, b: FlightModel) {
    return compareByArrival(a, b, -1);
}
export function compareByDepartureDesc(a: FlightModel, b: FlightModel) {
    return compareByDeparture(a, b, -1);
}
export function compareByDurationDesc(a: FlightModel, b: FlightModel) {
    return compareByDuration(a, b, -1);
}

export function compareByArrivalAsc(a: FlightModel, b: FlightModel) {
    return compareByArrival(a, b, 1);
}
export function compareByDepartureAsc(a: FlightModel, b: FlightModel) {
    return compareByDeparture(a, b, 1);
}
export function compareByDurationAsc(a: FlightModel, b: FlightModel) {
    return compareByDuration(a, b, 1);
}

function compareByArrival(a: FlightModel, b: FlightModel, direction: CompareDirection) {
    return compareByLeg(getLastLeg(a), getLastLeg(b), 'arrival', direction);
}

function compareByDeparture(a: FlightModel, b: FlightModel, direction: CompareDirection) {
    return compareByLeg(getFirstLeg(a), getFirstLeg(b), 'departure', direction);
}

function compareByDuration(a: FlightModel, b: FlightModel, direction: CompareDirection) {
    const amin = getTotalMinutes(a.duration);
    const bmin = getTotalMinutes(b.duration);
    if (amin > bmin) return direction;
    if (amin < bmin) return direction * -1;
    return 0;
}

function compareByLeg(a: Leg, b: Leg, property: keyof Pick<Leg, 'arrival' | 'departure'>, direction: CompareDirection) {
    return compareByTime(a[property].times.scheduled, b[property].times.scheduled, direction);
}
function compareByTime(a: IFlightTime, b: IFlightTime, direction: CompareDirection) {
    if (a.utc > b.utc) return direction;
    if (a.utc < b.utc) return direction * -1;
    return 0;
}
