from flask import abort, flash, redirect, render_template, url_for
from flask_login import current_user
from app import db
from app.models import TesseractOCRPipelineModel
from . import bp
from .forms import (
    CreateTesseractOCRPipelineModelForm,
    UpdateTesseractOCRPipelineModelForm
)


@bp.route('/')
def index():
    return redirect(url_for('contributions.index', _anchor='tesseract-ocr-pipeline-models'))


@bp.route('/create', methods=['GET', 'POST'])
def create():
    form = CreateTesseractOCRPipelineModelForm()
    if form.is_submitted():
        if not form.validate():
            return {'errors': form.errors}, 400
        try:
            topm = TesseractOCRPipelineModel.create(
                form.tesseract_model_file.data,
                compatible_service_versions=form.compatible_service_versions.data,
                description=form.description.data,
                publisher=form.publisher.data,
                publisher_url=form.publisher_url.data,
                publishing_url=form.publishing_url.data,
                publishing_year=form.publishing_year.data,
                is_public=False,
                title=form.title.data,
                version=form.version.data,
                user=current_user
            )
        except OSError:
            abort(500)
        db.session.commit()
        flash(f'Tesseract OCR Pipeline model "{topm.title}" created')
        return {}, 201, {'Location': url_for('.index')}
    return render_template(
        'contributions/tesseract_ocr_pipeline_models/create.html.j2',
        title='Create Tesseract OCR Pipeline Model',
        form=form
    )


@bp.route('/<hashid:tesseract_ocr_pipeline_model_id>', methods=['GET', 'POST'])
def entity(tesseract_ocr_pipeline_model_id):
    topm = TesseractOCRPipelineModel.query.get_or_404(tesseract_ocr_pipeline_model_id)
    if not (topm.user == current_user or current_user.is_administrator):
        abort(403)
    form = UpdateTesseractOCRPipelineModelForm(data=topm.to_json_serializeable())
    if form.validate_on_submit():
        form.populate_obj(topm)
        if db.session.is_modified(topm):
            flash(f'Tesseract OCR Pipeline model "{topm.title}" updated')
            db.session.commit()
        return redirect(url_for('.index'))
    return render_template(
        'contributions/tesseract_ocr_pipeline_models/entity.html.j2',
        title=f'{topm.title} {topm.version}',
        form=form,
        tesseract_ocr_pipeline_model=topm
    )