import { TimeTable } from './timetable.js';


/**
 * @template {{
 *   startTime: import('@silane/datetime').DateTime,
 *   endTime: import('@silane/datetime').DateTime,
 * }} T
 * @param {Iterable<T>} events
 * @param {Iterable<{
 *   startTime: import('@silane/datetime').DateTime,
 *   endTime: import('@silane/datetime').DateTime,
 * }>} availableHours
 * @param {import('@silane/datetime').DateTime} minTime
 * @param {import('@silane/datetime').DateTime} maxTime
 * @returns {{
 *   startTime: import('@silane/datetime').DateTime,
 *   endTime: import('@silane/datetime').DateTime,
 *   available: boolean, events: T[]
 * }[]}
 */
export function getTimeLine(events, availableHours, minTime, maxTime) {
    const timetable = new TimeTable();
    for(let event of events) {
        timetable.add(event.startTime, event.endTime,
                      {type: 'event', content: event});
    }
    for(let range of availableHours) {
        timetable.add(range.startTime, range.endTime,
                      {type: 'availableHour'});
    }

    const marker = {type: 'marker'};
    timetable.add(minTime, maxTime, marker);
    let segments = timetable.get();

    // markerが含まれるsegmentを探す
    let idx;
    for(idx = 0; !segments[idx].items.has(marker); ++idx);
    const startIdx = idx;
    for(
        idx = startIdx;
        idx < segments.length && segments[idx].items.has(marker); ++idx
    );
    const endIdx = idx;

    segments = segments.slice(startIdx, endIdx);
    segments = segments.map(x =>
        ({startTime: x.start, endTime: x.end, events: Array.from(x.items)})
    );

    segments = segments.map(({startTime, endTime, events}) => ({
        startTime, endTime,
        available: events.some(e => e.type === 'availableHour'),
        events: events.filter(e => e.type === 'event').map(e => e.content),
    }));

    return segments;
}
