export function segmentIsActive(segment, time) {
  return Number.isFinite(segment?.start)
    && Number.isFinite(segment?.end)
    && time >= segment.start
    && time < segment.end;
}

export function activeTrackSegments(
  tracks,
  time,
  { includeTypes = null, excludeTypes = [], requiredFields = {} } = {},
) {
  const included = includeTypes ? new Set(includeTypes) : null;
  const excluded = new Set(excludeTypes);
  return [...tracks]
    .sort((left, right) => (left.order || 0) - (right.order || 0))
    .flatMap(track => {
      if (track.visible === false) return [];
      if ((included && !included.has(track.type)) || excluded.has(track.type)) return [];
      const requiredField = requiredFields[track.type];
      return (track.segments || []).flatMap((segment, segmentIndex) => {
        if (!segmentIsActive(segment, time)) return [];
        if (requiredField && !segment[requiredField]) return [];
        return [{ track, segment, segmentIndex }];
      });
    });
}
