from flask import abort
from flask_login import current_user
from functools import wraps
from app.models import Corpus, CorpusFollowerAssociation


def corpus_follower_permission_required(*permissions):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            corpus_id = kwargs.get('corpus_id')
            corpus = Corpus.query.get_or_404(corpus_id)
            if current_user == corpus.user or current_user.is_administrator():
                return f(*args, **kwargs)
            if not current_user.is_following_corpus(corpus):
                abort(403)
            corpus_follower_association = CorpusFollowerAssociation.query.filter_by(corpus_id=corpus_id, follower_id=current_user.id).first_or_404()
            if not all([corpus_follower_association.role.has_permission(p) for p in permissions]):
                abort(403)
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def corpus_owner_or_admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        corpus_id = kwargs.get('corpus_id')
        corpus = Corpus.query.get_or_404(corpus_id)
        if current_user == corpus.user or current_user.is_administrator():
            return f(*args, **kwargs)
        abort(403)
    return decorated_function

