from flask import (
    abort,
    flash,
    redirect,
    render_template,
    send_from_directory,
    url_for
)
from flask_breadcrumbs import register_breadcrumb
from flask_login import login_required
import os
from app import db
from app.models import Corpus, CorpusFile, CorpusStatus
from ..decorators import corpus_follower_permission_required
from ..utils import corpus_endpoint_arguments_constructor as corpus_eac
from . import bp
from .forms import CreateCorpusFileForm, UpdateCorpusFileForm
from .utils import (
    corpus_file_dynamic_list_constructor as corpus_file_dlc
)


@bp.route('/<hashid:corpus_id>/files')
@register_breadcrumb(bp, '.entity.files', 'Files', endpoint_arguments_constructor=corpus_eac)
@login_required
def corpus_files(corpus_id):
    return redirect(url_for('.corpus', corpus_id=corpus_id, _anchor='files'))


@bp.route('/<hashid:corpus_id>/files/create', methods=['GET', 'POST'])
@register_breadcrumb(bp, '.entity.files.create', 'Create', endpoint_arguments_constructor=corpus_eac)
@login_required
@corpus_follower_permission_required('ADD_CORPUS_FILE')
def create_corpus_file(corpus_id):
    corpus = Corpus.query.get_or_404(corpus_id)
    form = CreateCorpusFileForm()
    if form.is_submitted():
        if not form.validate():
            response = {'errors': form.errors}
            return response, 400
        try:
            corpus_file = CorpusFile.create(
                form.vrt.data,
                address=form.address.data,
                author=form.author.data,
                booktitle=form.booktitle.data,
                chapter=form.chapter.data,
                editor=form.editor.data,
                institution=form.institution.data,
                journal=form.journal.data,
                pages=form.pages.data,
                publisher=form.publisher.data,
                publishing_year=form.publishing_year.data,
                school=form.school.data,
                title=form.title.data,
                mimetype='application/vrt+xml',
                corpus=corpus
            )
        except (AttributeError, OSError):
            abort(500)
        corpus.status = CorpusStatus.UNPREPARED
        db.session.commit()
        flash(f'Corpus File "{corpus_file.filename}" added', category='corpus')
        return '', 201, {'Location': corpus.url}
    return render_template(
        'corpora/files/create_corpus_file.html.j2',
        corpus=corpus,
        form=form,
        title='Add corpus file'
    )


@bp.route('/<hashid:corpus_id>/files/<hashid:corpus_file_id>', methods=['GET', 'POST'])
@register_breadcrumb(bp, '.entity.files.entity', '', dynamic_list_constructor=corpus_file_dlc)
@login_required
@corpus_follower_permission_required('UPDATE_CORPUS_FILE')
def corpus_file(corpus_id, corpus_file_id):
    corpus_file = CorpusFile.query.filter_by(corpus_id=corpus_id, id=corpus_file_id).first_or_404()
    form = UpdateCorpusFileForm(data=corpus_file.to_json_serializeable())
    if form.validate_on_submit():
        form.populate_obj(corpus_file)
        if db.session.is_modified(corpus_file):
            corpus_file.corpus.status = CorpusStatus.UNPREPARED
            db.session.commit()
            flash(f'Corpus file "{corpus_file.filename}" updated', category='corpus')
        return redirect(corpus_file.corpus.url)
    return render_template(
        'corpora/files/corpus_file.html.j2',
        corpus=corpus_file.corpus,
        corpus_file=corpus_file,
        form=form,
        title='Edit corpus file'
    )


@bp.route('/<hashid:corpus_id>/files/<hashid:corpus_file_id>/download')
@login_required
@corpus_follower_permission_required('VIEW')
def download_corpus_file(corpus_id, corpus_file_id):
    corpus_file = CorpusFile.query.filter_by(corpus_id=corpus_id, id=corpus_file_id).first_or_404()
    return send_from_directory(
        os.path.dirname(corpus_file.path),
        os.path.basename(corpus_file.path),
        as_attachment=True,
        attachment_filename=corpus_file.filename,
        mimetype=corpus_file.mimetype
    )
