import { TimeTrackingEntryType } from '../types/entry';
import { TimeTrackingEntryPrototype } from './timeTrackingEntry';

export class PairedEntry {
    public start?: TimeTrackingEntryPrototype;
    public end?: TimeTrackingEntryPrototype;

    static getPairedResults = (entries: TimeTrackingEntryPrototype[]): PairedEntry[] => {
        if (!entries?.length) {
            return [];
        }
        const pairedResults: PairedEntry[] = [];
        const sortedEntries = entries.sort((a, b) => b.time.getTime() - a.time.getTime());
        for (let i = 0; i < sortedEntries.length; i++) {
            const entry = sortedEntries[i];
            if (entry.type === TimeTrackingEntryType.END) {
                const nextEntry = sortedEntries[i + 1];
                if (nextEntry && nextEntry.type === TimeTrackingEntryType.START) {
                    i++; // Skipping next entry
                    pairedResults.push({ end: entry, start: nextEntry });
                } else {
                    pairedResults.push({ end: entry });
                }
            } else if (entry.type === TimeTrackingEntryType.START) {
                pairedResults.push({ start: entry });
            }
        }
        return pairedResults;
    };
}
