from typing import List
from typing import Optional


def present_menu(devices: List[dict], saved_device: Optional[dict] = None) -> dict:
    """ Format the menu of selectable microphones and receive selection from user.

    Parameters
    ----------
    devices : List[dict]
        Device logs for detected microphones

    saved_device : Optional[dict]
         The device log for the saved device - used to indicate on
         the menu the current saved device.

    Returns
    -------
    dict
        The device log for the user-selected device."""
    # Print the menu
    menuIndex = 0
    for device in devices:
        # If the user previously saved a device, indicate that in the menu with an asterisk
        isSavedSelection = int(saved_device['index']) == device['index'] \
            if saved_device is not None \
            else False
        savedSelectionText = '*' if isSavedSelection else ' '
        
        print('{}) {} {}'.format(str(menuIndex), savedSelectionText, device['name']))
        menuIndex = menuIndex + 1

    # Get the user's input and select the input device
    inputValid = False
    menuSelection = 0
    while not inputValid:
        menuInput = input(" >> ").strip()
        if menuInput.isdecimal():
            menuSelection = int(menuInput)
            if menuSelection <= menuIndex:
                inputValid = True
            else:
                print("invalid input")
        else:
            print("invalid input")
    return devices[menuSelection]