import copy


def sample_clips(videos, num_samples_per_video, sample_duration):
    """Extracts clips with given length from each video.
    Args:
        videos: List of video samples
        num_samples_per_video: Number of clips sampled for each video. If num_samples_per_video = 1 ,
            then all frames are returned for each video. If num_samples_per_video <= 0, then all sequential
            clips are sampled from video. If num_samples_per_video > 1, then clips are sampled uniformly.
        sample_duration: Number of frames in sampled clips. Actual value may be smaller for short clips.

    Returns: List of clip samples

    """
    videos = sorted(videos, key=lambda v: v['video'].split('/')[-1])
    clips = []
    for sample in videos:
        segment_start, segment_end = sample['segment']
        n_frames = segment_end - segment_start + 1

        if num_samples_per_video == 1:
            # use all frames from video
            sample['frame_indices'] = list(range(segment_start, segment_end + 1))
            clips.append(sample)

        else:

            num_samples = num_samples_per_video
            if num_samples_per_video <= 0:
                # Use all clips of sample_duration or the whole video if it's short enough.
                step = 1
                num_samples = max(1, n_frames - sample_duration + 1)
            else:
                step = max(1, (n_frames - sample_duration) // (num_samples_per_video - 1))

            for clip_start in range(segment_start, segment_start + step * num_samples, step):
                sampled_clip = copy.deepcopy(sample)
                clip_end = min(segment_end + 1, clip_start + sample_duration)
                sampled_clip['frame_indices'] = list(range(clip_start, clip_end))
                if sampled_clip['frame_indices']:
                    clips.append(sampled_clip)

    return clips