import itertools


def cycle_ring_atom_key_to_front(keys, key, end_key=None):
    """ helper function to cycle ring atom keys until one is in front

    :param keys: ring keys
    :parm key: the key to cycle to the font
    :param end_key: optionally, ensure that another key is the last key in the
        ring; note that this is only possible if key and end_key are adjacent
    """
    assert key in keys, ("{:d} is not in {:s}".format(key, str(keys)))
    keys = tuple(itertools.islice(
        itertools.dropwhile(lambda x: x != key, itertools.cycle(keys)),
        len(keys)))

    if end_key is not None and keys[-1] != end_key:
        assert keys[1] == end_key, (
            "end_key {:d} is not adjacent to {:d} in the ring"
            .format(key, end_key))
        keys = list(reversed(keys))
        keys = cycle_ring_atom_key_to_front(keys, key)

    return keys