import time


def should_refresh_time(event_time, last_refresh_time, refresh_after_mins=60):
    """
    The clock on the PyPortal drifts, and should be refreshed
    from the internet periodically for accuracy.

    We want to refresh the local time when:
    - The local time isn't set
    - After refresh_after_mins have passed
    - If the event time hasn't passed

    Args:
        event_time (time.struct_time): Time of the event.
        last_refresh_time (time.monotonic): Time local time
            was last refreshed from the internet.
        refresh_after_mins (int, optional): How many minutes to wait
            between refreshing from the internet. Defaults to 60.

    Returns:
        bool: If the local device time should be refreshed from
            the internet.
    """
    just_turned_on = not last_refresh_time
    if just_turned_on:
        print("Refreshing time: PyPortal just turned on.")
        return True

    time_since_refresh = time.monotonic() - last_refresh_time
    refresh_time_period_expired = time_since_refresh > refresh_after_mins * 60
    if refresh_time_period_expired:
        print(
            "Refreshing time: last refreshed over {} mins ago.".format(
                refresh_after_mins
            )
        )
        return True

    remaining_time = time.mktime(event_time) - time.mktime(time.localtime())
    is_event_over = remaining_time and remaining_time < 0
    if is_event_over:
        print("Won't refresh time: event over.")
        return False