import { PeriodFlightTimeModel } from './period-flight-time.model';

export interface Duration {
    days: number;
    hours: number;
    minutes: number;
}

export const zeroDuration: Duration = { days: 0, hours: 0, minutes: 0 };

export function getPeriodDuration(period?: PeriodFlightTimeModel) {
    return getDuration(period?.start?.local, period?.end?.local) || zeroDuration;
}

export function getDuration(from?: Date | string, to?: Date | string): Duration | undefined {
    if (!from || !to) return undefined;
    return getDurationMs(new Date(to).getTime() - new Date(from).getTime());
}

export function getTotalMinutes({ days = 0, hours = 0, minutes = 0 }: Duration = {} as any) {
    return minutes + hours * 60 + days * 24 * 60;
}

export function getDurationMs(ms: number): Duration {
    ms = ms / 1000 / 60; // ms / milliseconds / seconds
    const days = Math.floor(ms / (60 * 24));
    const hours = Math.floor((ms / 60) % 24);
    const minutes = Math.floor(ms % 60);
    return { days, hours, minutes: minutes };
}

export function getDurationDiff(first: Duration, next: Duration): Duration {
    if (!first || !next) return zeroDuration;

    const totalMinutes = getTotalMinutes(next) - getTotalMinutes(first);
    return getDurationMs(totalMinutes * 60 * 1000);
}
