import random
import copy


def replace_rests(measures):
    """
    Removes all rests from measures, and replaces them with a nearby note

    Args:
        measures (List[List[AnalyzedNote]]) Analyzed notes grouped in measures

    Returns:
        altered_measures(List[List[AnalyzedNote]]): list of measures with replaced rests.
    """
    altered_measures = []

    for measure in measures:
        m = []

        # find all non-rest notes in measure
        non_rest_elements = list(filter(lambda x: not x.is_rest(), measure))

        if len(non_rest_elements) == 0:
            if altered_measures:
                measure = altered_measures[-1]
                altered_measures.append(measure)
                continue
            else:
                continue

        for i in range(len(measure)):
            element = measure[i]

            if element.is_rest():
                replace_element = random.choice(non_rest_elements)
                new_element = copy.deepcopy(replace_element.element)
                m.append(element.copy(element=new_element))

            else:
                m.append(element)

        altered_measures.append(m)

    return altered_measures