from flask import abort, jsonify, request
from flask_login import current_user, login_required
from app import db
from app.decorators import content_negotiation
from app.models import (
    Corpus,
    CorpusFollowerAssociation,
    CorpusFollowerRole,
    User
)
from ..decorators import corpus_owner_or_admin_required
from . import bp


@bp.route('/<hashid:corpus_id>/followers', methods=['POST'])
@login_required
@corpus_owner_or_admin_required
@content_negotiation(consumes='application/json', produces='application/json')
def create_corpus_followers(corpus_id):
    usernames = request.json
    if not (isinstance(usernames, list) or all(isinstance(u, str) for u in usernames)):
        abort(400)
    corpus = Corpus.query.get_or_404(corpus_id)
    for username in usernames:
        user = User.query.filter_by(username=username, is_public=True).first_or_404()
        user.follow_corpus(corpus)
    db.session.commit()
    resonse_data = {
        'message': f'Users are now following "{corpus.title}"',
        'category': 'corpus'
    }
    response = jsonify(resonse_data)
    response.status_code = 200
    return response


@bp.route('/<hashid:corpus_id>/followers/<hashid:follower_id>/role', methods=['PUT'])
@login_required
@corpus_owner_or_admin_required
@content_negotiation(consumes='application/json', produces='application/json')
def update_corpus_follower_role(corpus_id, follower_id):
    role_name = request.json
    if not isinstance(role_name, str):
        abort(400)
    cfr = CorpusFollowerRole.query.filter_by(name=role_name).first()
    if cfr is None:
        abort(400)
    cfa = CorpusFollowerAssociation.query.filter_by(corpus_id=corpus_id, follower_id=follower_id).first_or_404()
    cfa.role = cfr
    db.session.commit()
    resonse_data = {
        'message': f'User "{cfa.follower.username}" is now {cfa.role.name}',
        'category': 'corpus'
    }
    response = jsonify(resonse_data)
    response.status_code = 200
    return response


@bp.route('/<hashid:corpus_id>/followers/<hashid:follower_id>', methods=['DELETE'])
@login_required
@content_negotiation(produces='application/json')
def delete_corpus_follower(corpus_id, follower_id):
    corpus = Corpus.query.get_or_404(corpus_id)
    follower = User.query.get_or_404(follower_id)
    if not (corpus.user == current_user or follower == current_user or current_user.is_administrator()):
        abort(403)
    if not follower.is_following_corpus(corpus):
        abort(409)
    follower.unfollow_corpus(corpus)
    db.session.commit()
    response_data = {
        'message': \
            f'"{follower.username}" is not following "{corpus.title}" anymore',
        'category': 'corpus'
    }
    response = jsonify(response_data)
    response.status_code = 200
    return response
