from flask import redirect, url_for, request, flash, abort
from flask_login import login_required, current_user
from app import app, db
from app.models.notification import Notification
from app.utils.render import render


@app.route('/notifications', methods=['GET'])
@login_required
def list_notifications():
    notifications = current_user.notifications
    return render('account/notifications.html', notifications=notifications)


@app.route('/notifications/supprimer/<id>', methods=['GET'])
@login_required
# TODO: [SECURITY ISSUE] prevent CSRF
def delete_notification(id=None):
    # Try to convert id to int
    try:
        id = int(id)
    except ValueError:
        pass

    if type(id) == int:
        notification = Notification.query.get(id)
        if notification:
            # Only current user or admin can delete notifications
            if notification.owner_id == current_user.id:
                notification.delete()
                db.session.commit()
                return redirect(url_for('list_notifications'))
            elif 'delete_notification' in current_user.privs:
                notification.delete()
                db.session.commit()
                if request.referrer:
                    return redirect(request.referrer)
                return redirect(url_for('adm'))
            else:
                abort(403)
        abort(404)
    elif id == "all":
        for n in current_user.notifications:
            n.delete()
        db.session.commit()
        return redirect(url_for('list_notifications'))
        # TODO: add something to allow an admin to delete all notifs for a user
        # with a GET parameter
    else:
        abort(404)
