# Path: amivapi/events/queue.py
# def update_waiting_list(event_id):
#     """Fill up missing people in an event with people from the waiting list.
#     This gets triggered by different hooks, whenever the list needs to be
#     updated.
# 
#     1. After a new signup is created.
#     2. After a signup was deleted.
#     3. After an external signup was confirmed.
# 
#     Returns:
#         list: ids of all singups which are newly accepted.
#     """
#     id_field = current_app.config['ID_FIELD']
#     lookup = {id_field: event_id}
#     event = current_app.data.find_one('events', None, **lookup)
# 
#     accepted_ids = []
# 
#     if event['selection_strategy'] == 'fcfs':
#         lookup = {'event': event_id, 'accepted': True}
#         signup_count = (
#             current_app.data.driver.db['eventsignups'].count_documents(lookup))
# 
#         # 0 spots == infinite spots
#         if event['spots'] == 0 or signup_count < event['spots']:
#             lookup = {'event': event_id, 'accepted': False, 'confirmed': True}
#             new_list = current_app.data.driver.db['eventsignups'].find(
#                 lookup).sort('_created', ASCENDING)
# 
#             if event['spots'] > 0:
#                 to_accept = new_list.limit(event['spots'] - signup_count)
#             else:
#                 # infinite spots, so just accept everyone
#                 to_accept = new_list
# 
#             for new_accepted in to_accept:
#                 accepted_ids.append(new_accepted['_id'])
#                 # Set accepted flag
#                 current_app.data.update('eventsignups', new_accepted[id_field],
#                                         {'accepted': True}, new_accepted)
# 
#                 # Notify user
#                 notify_signup_accepted(event, new_accepted)
# 
#     return accepted_ids
# 
# Path: amivapi/events/utils.py
# def get_token_secret():
#     db = current_app.data.driver.db['config']
#     result = db.find_one({'TOKEN_SECRET': {'$exists': True}})
#     return result['TOKEN_SECRET']


from bson import ObjectId
from eve.methods.delete import deleteitem_internal
from eve.methods.patch import patch_internal
from flask import Blueprint, current_app, redirect
from itsdangerous import BadSignature, URLSafeSerializer
from amivapi.events.queue import update_waiting_list
from amivapi.events.utils import get_token_secret
    We try to confirm the specified signup and redirect to a webpage.
    """
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    except BadSignature:
        return "Unknown token"

    patch_internal('eventsignups', {'confirmed': True},
                   skip_validation=True, concurrency_check=False,
                   **{current_app.config['ID_FIELD']: signup_id})

    # Now the user may be able to get accepted, so update the events waiting
    # list
    lookup = {current_app.config['ID_FIELD']: signup_id}
    signup = current_app.data.find_one('eventsignups', None, **lookup)

    update_waiting_list(signup['event'])

    redirect_url = current_app.config.get('EMAIL_CONFIRMED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['CONFIRM_TEXT']


@email_blueprint.route('/delete_signup/<token>')
def on_delete_signup(token):
    """Endpoint to delete signups via email"""
    try:

# Path: amivapi/events/queue.py
# def update_waiting_list(event_id):
#     """Fill up missing people in an event with people from the waiting list.
#     This gets triggered by different hooks, whenever the list needs to be
#     updated.
# 
#     1. After a new signup is created.
#     2. After a signup was deleted.
#     3. After an external signup was confirmed.
# 
#     Returns:
#         list: ids of all singups which are newly accepted.
#     """
#     id_field = current_app.config['ID_FIELD']
#     lookup = {id_field: event_id}
#     event = current_app.data.find_one('events', None, **lookup)
# 
#     accepted_ids = []
# 
#     if event['selection_strategy'] == 'fcfs':
#         lookup = {'event': event_id, 'accepted': True}
#         signup_count = (
#             current_app.data.driver.db['eventsignups'].count_documents(lookup))
# 
#         # 0 spots == infinite spots
#         if event['spots'] == 0 or signup_count < event['spots']:
#             lookup = {'event': event_id, 'accepted': False, 'confirmed': True}
#             new_list = current_app.data.driver.db['eventsignups'].find(
#                 lookup).sort('_created', ASCENDING)
# 
#             if event['spots'] > 0:
#                 to_accept = new_list.limit(event['spots'] - signup_count)
#             else:
#                 # infinite spots, so just accept everyone
#                 to_accept = new_list
# 
#             for new_accepted in to_accept:
#                 accepted_ids.append(new_accepted['_id'])
#                 # Set accepted flag
#                 current_app.data.update('eventsignups', new_accepted[id_field],
#                                         {'accepted': True}, new_accepted)
# 
#                 # Notify user
#                 notify_signup_accepted(event, new_accepted)
# 
#     return accepted_ids
# 
# Path: amivapi/events/utils.py
# def get_token_secret():
#     db = current_app.data.driver.db['config']
#     result = db.find_one({'TOKEN_SECRET': {'$exists': True}})
#     return result['TOKEN_SECRET']


# Path: amivapi/events/email_links.py
from bson import ObjectId
from eve.methods.delete import deleteitem_internal
from eve.methods.patch import patch_internal
from flask import Blueprint, current_app, redirect
from itsdangerous import BadSignature, URLSafeSerializer
from amivapi.events.queue import update_waiting_list
from amivapi.events.utils import get_token_secret

    We try to confirm the specified signup and redirect to a webpage.
    """
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    except BadSignature:
        return "Unknown token"

    patch_internal('eventsignups', {'confirmed': True},
                   skip_validation=True, concurrency_check=False,
                   **{current_app.config['ID_FIELD']: signup_id})

    # Now the user may be able to get accepted, so update the events waiting
    # list
    lookup = {current_app.config['ID_FIELD']: signup_id}
    signup = current_app.data.find_one('eventsignups', None, **lookup)

    update_waiting_list(signup['event'])

    redirect_url = current_app.config.get('EMAIL_CONFIRMED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['CONFIRM_TEXT']


@email_blueprint.route('/delete_signup/<token>')
def on_delete_signup(token):
    """Endpoint to delete signups via email"""
    try:

        s = URLSafeSerializer(get_token_secret())