from flask import current_app, jsonify
from flask_login import login_required
from threading import Thread
from app import db
from app.decorators import content_negotiation
from app.models import CorpusFile
from ..decorators import corpus_follower_permission_required
from . import bp


@bp.route('/<hashid:corpus_id>/files/<hashid:corpus_file_id>', methods=['DELETE'])
@login_required
@corpus_follower_permission_required('REMOVE_CORPUS_FILE')
@content_negotiation(produces='application/json')
def delete_corpus_file(corpus_id, corpus_file_id):
    def _delete_corpus_file(app, corpus_file_id):
        with app.app_context():
            corpus_file = CorpusFile.query.get(corpus_file_id)
            corpus_file.delete()
            db.session.commit()

    corpus_file = CorpusFile.query.filter_by(corpus_id=corpus_id, id=corpus_file_id).first_or_404()
    thread = Thread(
        target=_delete_corpus_file,
        args=(current_app._get_current_object(), corpus_file.id)
    )
    thread.start()
    response_data = {
        'message': f'Corpus File "{corpus_file.title}" marked for deletion',
        'category': 'corpus'
    }
    response = jsonify(response_data)
    response.status_code = 202
    return response
