# 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
# -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
#          you to buy us beer if we meet and you like the software.
"""Email confirmation logic.

Needed when external users want to sign up for public events or users want to
sign off via links.
"""


email_blueprint = Blueprint('emails', __name__)


def add_confirmed_before_insert(items):
    """Add the confirmed field to a event signup before it is inserted to the
    database. We accept all registered users instantly, others need to click the
    confirmation link first"""
    for item in items:
        if item.get('user', None) is None:
            item['confirmed'] = False
        else:

# 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

# -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
#          you to buy us beer if we meet and you like the software.
"""Email confirmation logic.

Needed when external users want to sign up for public events or users want to
sign off via links.
"""


email_blueprint = Blueprint('emails', __name__)


def add_confirmed_before_insert(items):
    """Add the confirmed field to a event signup before it is inserted to the
    database. We accept all registered users instantly, others need to click the
    confirmation link first"""
    for item in items:
        if item.get('user', None) is None:
            item['confirmed'] = False
        else:

            item['confirmed'] = True