def METHOD_NAME(lang_code, curr_id, category, intersection):
    if category is CATEGORY_ALL and not intersection:
        next_id = curr_id
        for i in range(3): # super paranoid :)
            next_id = select_random_id(lang_code, category, intersection)
            if next_id != curr_id:
                break
        return next_id
    if category is not CATEGORY_ALL:
        ret = database.query_next_id_in_category(
            lang_code, curr_id, category.id)
    else:
        assert intersection
        ret = database.query_next_id_in_intersection(
            lang_code, curr_id, intersection)
    if ret is None:
        # curr_id doesn't belong to the category or intersection
        return None
    assert ret and len(ret) == 1
    return ret[0]