import { moment } from '@humand-packages/common';

import { PairedEntry } from '../models/PairedEntry';
import { TimeTrackingEntryPrototype } from '../models/timeTrackingEntry';

const MINUTES_IN_HOUR = 60;
const ROUNDING_OFFSET_SECONDS = 30;

export const calculateWorkedHours = (entries: TimeTrackingEntryPrototype[]): number => {
    return PairedEntry.getPairedResults(entries).reduce((total, pair) => {
        const pairTotal =
            pair.start && pair.end
                ? moment(pair.end.time).add(ROUNDING_OFFSET_SECONDS, 'seconds').diff(pair.start.time, 'minutes') / MINUTES_IN_HOUR
                : 0;
        return total + pairTotal;
    }, 0);
};

// PairedEntry.getPairedResults returns pairs sorted by time DESC, so the first START without an END is the most recent.
export const getLatestOpenStart = (allEntries: TimeTrackingEntryPrototype[]): TimeTrackingEntryPrototype | undefined => {
    return PairedEntry.getPairedResults(allEntries).find((pair) => pair.start && !pair.end)?.start;
};
